Highcharts: create multiple series grouped my month and year using JSON data

我的未来我决定 提交于 2020-01-16 18:20:44

问题


I am trying to create a line, spline chart using JSON data. I want multiple series but I am confused on how to do that. Right now I am able to create the multiple series when the date is in 2019-07-06 format. I also have a JSON that has a column for the month and a column for the year Please help on how I can fix this. Right now I only have the code for group by day.

JSON Data:

[ 
 { "month": 6, 
   "year": 2019, 
   "starts": 21278998, 
   "completes": 9309458 
 }, 
 { "month": 7, 
   "year": 2019, 
   "starts": 38850115, 
   "completes": 17790105 
 } 
]

I used the solution for the date format 2019-07-06 provided in this fiddle: https://jsfiddle.net/BlackLabel/tjLvh89b/

Please help with how I can create a chart for the Month, Year on the x-Axis.


回答1:


You can achieve it simply by creating a Date object using different parameters.

Instead of the string date parameter new Date('2019-07-07') use year and month as separate parameters like that: new Date(2019, 7).

Code:

var json = [{
  month: 6,
  year: 2019,
  starts: 21278998,
  completes: 9309458
}, {
  month: 7,
  year: 2019,
  starts: 38850115,
  completes: 17790105
}];

var series1 = {
    name: 'starts',
    data: []
  },
  series2 = {
    name: 'completes',
    data: []
  };

json.forEach(elem => {
  series1.data.push({
    x: +new Date(elem.year, elem.month),
    y: elem.starts
  });

  series2.data.push({
    x: +new Date(elem.year, elem.month),
    y: elem.completes
  });
});

Highcharts.chart('container', {
  chart: {
    type: 'spline'
  },
  xAxis: {
    type: 'datetime'
  },
  series: [
    series1,
    series2
  ]
});

Demo:

  • https://jsfiddle.net/BlackLabel/xtefuLsp/1/

Date object reference:

  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date


来源:https://stackoverflow.com/questions/57295753/highcharts-create-multiple-series-grouped-my-month-and-year-using-json-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!