Search code examples
amcharts

Series with multiple objects in JSON file in Amcharts


I'm trying to create 2 series for my chart in amcharts. I have the following JSON:

[
{"equipament":"pir1","watts":48.0,"currentdate":"2020-02-06T21:11:55"},
{"equipament":"pir2","watts":16.0,"currentdate":"2020-02-06T21:11:55"},
{"equipament":"pir1","watts":3.0,"currentdate":"2020-02-06T21:16:52"},
{"equipament":"pir2","watts":12.0,"currentdate":"2020-02-06T21:16:52"}
]

I need to create a graph where on my X axis will be the currentdate field, and on the Y axis will be the watts field, but I need to take into account the equipament field.

I'm using typescript + angular in my development. What I managed to do:

 let chart = am4core.create("chartdiv", am4charts.XYChart);

  chart.data = [
{"equipament":"pir1","watts":48.0,"currentdate":"2020-02-06T21:11:55"},
{"equipament":"pir2","watts":16.0,"currentdate":"2020-02-06T21:11:55"},
{"equipament":"pir1","watts":3.0,"currentdate":"2020-02-06T21:16:52"},
{"equipament":"pir2","watts":12.0,"currentdate":"2020-02-06T21:16:52"}
  ];

  chart.dateFormatter.inputDateFormat = "yyyy-MM-dd HH:mm";

  // Create axes
  let dateAxis = chart.xAxes.push(new am4charts.DateAxis());
  dateAxis.tooltipDateFormat = "yyyy-MM-dd HH:mm";

  let valueAxis = chart.yAxes.push(new am4charts.ValueAxis());

  // Create series PIR1
  let series = chart.series.push(new am4charts.LineSeries());
  series.dataFields.valueY = "watts";
  series.dataFields.dateX = "currentdate";
  series.tooltipText = "{equipament}: [bold]{watts}[/]"
  series.name = "pir1";

  // Create series PIR2
  let series2 = chart.series.push(new am4charts.LineSeries());
  series2.dataFields.valueY = "watts";
  series2.dataFields.dateX = "currentdate";
  series2.tooltipText = "{equipament}: [bold]{watts}[/]"
  series2.name = "pir2";

  chart.cursor = new am4charts.XYCursor();
  chart.cursor.xAxis = dateAxis;
  chart.cursor.lineY.disabled = true;
  valueAxis.cursorTooltipEnabled = false;
  chart.scrollbarX = new am4core.Scrollbar();

  chart.legend = new am4charts.Legend();

  this.chart = chart;

However, when checking the graph, the series are overlapping. I believe I have to add some code to link to the equipament field. I already searched the amcharts documentation, but I didn't find anything about it. I appreciate that I can help.


Solution

  • amCharts can't filter out data for each series by specific key/value.

    The easiest way is to assign data to each series individually:

    series.data = [
      {"equipament":"pir1","watts":48.0,"currentdate":"2020-02-06T21:11:55"},
      {"equipament":"pir1","watts":3.0,"currentdate":"2020-02-06T21:16:52"}
    ];
    
    series2.data =  [
      {"equipament":"pir2","watts":16.0,"currentdate":"2020-02-06T21:11:55"},
      {"equipament":"pir2","watts":12.0,"currentdate":"2020-02-06T21:16:52"}
    ];
    

    This way you don't have to set chart.data at all.