How can I incorporate multiple graphs into my AmCharts display?

I am new to using amcharts and have successfully implemented a code snippet to generate two graphs in a chart. The charts are loaded from an external data source specified in the code.

 var chart = AmCharts.makeChart("chartdiv", {
  "type": "serial",
  "dataLoader": {
    "url": "https://s3-us-west-2.amazonaws.com/s.cdpn.io/218423/data1.json"
  },
  "valueAxes": [{
    "gridColor": "#FFFFFF",
    "gridAlpha": 0.2,
    "dashLength": 0
  }],
  "gridAboveGraphs": true,
  "startDuration": 1,
  "graphs": [{
    "balloonText": "[[category]]: <b>[[value]]</b>",
    "fillAlphas": 0.8,
    "lineAlpha": 0.2,
    "type": "column",
    "valueField": "visits"
  }],
  "chartCursor": {
    "categoryBalloonEnabled": false,
    "cursorAlpha": 0,
    "zoomable": false
  },
  "categoryField": "country",
  "categoryAxis": {
    "gridPosition": "start",
    "gridAlpha": 0,
    "tickPosition": "start",
    "tickLength": 20
  }
});

function setDataSet(dataset_url) {
  AmCharts.loadFile(dataset_url, {}, function(data) {
    chart.dataProvider = AmCharts.parseJSON(data);
    chart.validateData();
  });

The current setup is functioning well with two graphs, but I now aim to dynamically add multiple graphs without pre-defining the number of graphs. How can I achieve this flexibility in amcharts? Any guidance on this matter would be greatly appreciated.

Answer №1

If you are already aware of the categoryField in advance, utilize the dataLoader's complete callback to examine your newly assigned dataProvider array and generate graphs based on the keys within the array object.

  "dataLoader": {
    "url": "https://s3-us-west-2.amazonaws.com/s.cdpn.io/t-160/SO-41015973.json",
    "complete": function(chart) {
      // Identify potential valueFields after filtering out the categoryField
      var valueFields = Object.keys(chart.dataProvider[0]).filter(function(value) {
        return value !== chart.categoryField;
      });
      // Generate the graphs
      valueFields.forEach(function(valueField) {
        chart.graphs.push({
          "valueField": valueField,
          "type": "column",
          "balloonText": "[[category]]: <b>[[value]]</b>",
          "fillAlphas": 0.8,
          "lineAlphas": 0.2
        })
      });
    }
  },

I included an additional field in your data and produced a codepen demo to demonstrate that this method is effective.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for validating an email address using ReactJS

I'm currently working on customizing the email verification process for a signup form in ReactJS. My goal is to replace the default email verification with my own validation criteria. Initially, I want to ensure that the entered email address contains ...

Can React Slick be configured to display a Carousel within another Carousel?

Can React Slick support a Carousel within another Carousel? import Slider from "react-slick"; <Slider {...settings} > <div/> <div> <Slider {...settings} > ...

exploring div element(s) with jQuery

My HTML page contains multiple div elements in the body. I have also included buttons with associated click functions in jQuery to change the background-color of a div element based on the button pressed. However, I'm facing an issue at the 'term ...

Why does the width of my image appear differently on an iPhone compared to other devices?

I recently encountered an issue with the responsiveness of an image on my website. While it displayed correctly on Android and desktop devices, the image appeared distorted on iPhones as if the CSS width attribute was not applied properly. This problem spe ...

showing console logs before initializing preferences may lead to inaccurate results

My Content Management System (CMS) is WordPress. Recently, after making some changes, I encountered an error on a specific page: An error occurred: loading pref showConsoleLogs before prefs were initialised, leading to incorrect results being displayed - ...

Troubleshooting: Issues with locating CSS and JS files (404 error) while utilizing URL parameters within Django platform

I've designed a dashboard page that showcases various graphs. The page automatically updates the graph data every hour. You can access the page at the following URL: http://localhost/dashboard I'd like to give users the option to specify the ...

JavaScript and jQuery syntax are essential for web development. Understanding how

I've been searching everywhere but couldn't find syntax similar to this: var mz = jQuery.noConflict(); mz('#zoom01, .cloud-zoom-gallery').CloudZoom(); This basically means: jQuery.noConflict()('#zoom01, .cloud-zoom-gallery') ...

Retrieving data from a parent object within an iframe on a different origin

In order to incorporate a feature on various websites, I am looking to embed an iframe with JavaScript. This iframe should have the ability to interact with the parent object and display or hide certain elements on the webpage. The main HTML file includes ...

Using AJAX in JavaScript within an HTML document is a valuable skill to have

I have the following JavaScript function that I need to call the /print2 function without clicking any buttons. I attempted to use Ajax for this, but I am new to Ajax and JavaScript. Can you help me identify where the issue might be? Thank you... <scr ...

A guide on transferring documents between collections using Mongoose and MongoDB

I have a list of tasks that includes both completed and incomplete items. Additionally, I have two buttons - one for deleting an item (which is functional) and the other for marking an item as done or not. I am struggling with creating a function to move ...

I'm trying to figure out the best way to successfully pass a prop to another component in TypeScript without running into the frustrating issue of not being able to

I have been facing an issue while trying to pass a prop from a custom object I have defined. The structure of the object is as follows: export type CustomObjectType = { data?: DataObject }; export type DataObject = { id: number; name: stri ...

Accessing feedback from Reddit's API

After writing some code to search Reddit's API with a specific query, I now want it to display comments as well. Inside my $.getJSON statement that retrieves each title/post based on the search query, I have the following nested code block. The goal i ...

Is there a way to guide users to their designated page on Node.js?

My goal is to seamlessly redirect users to their designated pages based on their role. If the user is a regular user, they should be redirected to the user menu. On the other hand, if it's an employee, they should be directed to the employee menu. E ...

Guide on transmitting data from a child component to a parent object in Vue.js?

When I attempt to utilize a child component with custom form inputs and emit those values to the parent component, I encounter an issue where one input value disappears when another input value is entered. Let me showcase some code: Child Component <tem ...

Prevent parent element from changing color when child element is clicked

Check out my HTML: .imageURL:active .image_submit_div { background-color: #ccc; } .image_submit_div:active { background-color: #e6e6e6; } <div class="image_div"> <label for="id_image" class="image_submit_div"> <h3>+ add ...

JavaScript code for the submit button to proceed or halt the form submission

Within my JSP file, I have the following code snippet: <input type="submit" value="Transfer ULD" onclick="doSomething();" name="_eventId_transferULDTransition"/> The doSomething() function mentioned above is a JavaScript method. function doSomethi ...

Apple Safari 14.0.3 restricts JavaScript from setting a cookie expiry date beyond one week from the current date

This is my second time reaching out with this question, but after plenty of trial and error experimentation, I have gathered much more information to share. I have been attempting different methods to set a cookie in Safari using JavaScript 'document ...

Issue with Select2: When using a remote select2 control, the tab key press does not allow for the selection of the highlighted

I have set up select2 to load ajax data into select2 based on the example provided in this link Load ajax data into select2. In the example, I can type text, use arrow keys to navigate, and then hit tab to select the highlighted item. However, in my case, ...

Hiding and displaying DIVs on a single HTML page using VueJs 2

I am currently working on building an application that is not a single page application. As I develop my project, I have several div elements on the page that I want to toggle visibility step by step. Below is the snippet of my code: <div v-if="sect ...

Ways to trigger a server function in JavaScript upon closing a browser tab or the entire browser

How can I trigger a server function when closing a browser tab or window using JavaScript? Similar to this image //Below is the code for my server-side function: public ActionResult DeleteNotPostedImage(string folder , string PostID) { folder ...