Highcharts 动态生成series

Highcharts 动态生成series

场景

工作中遇到需要动态创建折线图,并赋值,并非后台组装直接data:data,需要格式化数据,并动态组装

代码如下

  • 后端(JAVA)
LineChart lineChart = new LineChart();
lineChart.setProName("小黑");
lineChart.setProData("[4,7,-5,5,9]");
LineChart lineChart1 = new LineChart();
lineChart1.setProName("小白");
lineChart1.setProData("[2,-4,-3,6,8]");
LineChart lineChart2 = new LineChart();
lineChart2.setProName("小灰");
lineChart2.setProData("[1,4,-5,7,4]");
List<LineChart> lineCharts = new ArrayList<>();
lineCharts.add(lineChart1);
lineCharts.add(lineChart2);
lineCharts.add(lineChart);
  • 前端(JS)
$.getJSON('/server_address', function (data) {
     var series = [];

     for(i=0; i<data.length; i++) {
         console.log(data[i].proData);
         series.push({"name": data[i].proName, "data": eval(data[i].proData)});
     }

     chart = Highcharts.chart('container2', {
         chart: {
             zoomType: 'x',
             type: 'area'
         },
         title: {
             text: '任务创建情况'
         },
         subtitle: {
             text: document.ontouchstart === undefined ?
                     '鼠标拖动可以进行缩放' : '手势操作进行缩放'
         },
         xAxis: {
             type: 'datetime',
             dateTimeLabelFormats: {
                 millisecond: '%H:%M:%S.%L',
                 second: '%H:%M:%S',
                 minute: '%H:%M',
                 hour: '%H:%M',
                 day: '%m-%d',
                 week: '%m-%d',
                 month: '%Y-%m',
                 year: '%Y'
             }
         },
         tooltip: {
             xDateFormat: '%Y-%m-%d'
         },
         yAxis: {
             title: {
                 text: '数量'
             }
         },
         plotOptions: {
             area: {
                 fillColor: {
                     linearGradient: {
                         x1: 0,
                         y1: 0,
                         x2: 0,
                         y2: 1
                     },
                     stops: [
                         [0, Highcharts.getOptions().colors[0]],
                         [1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')]
                     ]
                 },
                 marker: {
                     radius: 2
                 },
                 lineWidth: 1,
                 states: {
                     hover: {
                         lineWidth: 1
                     }
                 },
                 threshold: null
             }
         },
         series: series
     });
 });
  • data 数据格式
[1,4,-5,7,4]
// 后台可以由Java List对象组装,然后调用toString()函数获得

你可能感兴趣的:(hcharts)