Search code examples
amcharts

How to create a chart with a variable number of lines based on the data loaded via chart.dataSource.url


I have a chart with some data loaded through an ajax request through

chart.dataSource.url = "...my url...";

It works as long as i specify every line i want to draw like this.

var chartLine1 = chart.series.push(new am4charts.LineSeries());
chartLine1.dataFields.valueY = "pies_eaten";
chartLine1.dataFields.dateX = "date";

But i have a variable number of lines based on the results of the dataSource load. Is it possible to get the data array/object before the chart renders or to get amCharts to create one line for field?


Solution

  • Please check out our guide on manipulating external data. Using the dataSource's "parseended" event, you can manipulate the data directly or by re-assigning it before it gets passed off to the chart for consumption.

    E.g. our demo on using JSON dataSource has data from 2004-2012, we can just pass a new array to the dataSource's data:

    chart.dataSource.events.on("parseended", function(event) {
      // Original demo originally has 19 data items, ranging from 1994 through 2012,
      // this should set it to 1999 through 2008:
      event.target.data = event.target.data.slice(5,15);
    });
    

    With the above, it'll show a line from 1999 through 2008:

    https://codepen.io/team/amcharts/pen/6a0026c6cc01406db3a178bd6dd3f931