在Highcharts中为多个类别解析CSV

时间:2015-10-08 15:20:21

标签: javascript jquery csv highcharts

我调用Web服务来获取如下所示的数据:

Timestamp,Speed1,Speed2
10/5/2015 12:00:00 AM,86,46.2
10/5/2015 1:00:00 AM,78,51
10/5/2015 2:00:00 AM,77,52
10/5/2015 3:00:00 AM,80,49
10/5/2015 4:00:00 AM,112,42
10/5/2015 5:00:00 AM,79,50

我想生成一个包含两个类别的折线图,每个类别一个"速度",时间在x轴上,速度在y轴上。我无法解析CSV以生成Highcharts系列。目前,当我这样做时,我可以看到一个类别:

 $.get('GetSummaries.asmx/GetSummaryCsv', { }, function (csv) {

            var speedSeries = [];

            var lines = csv.trim().split('\n');
            $.each(lines, function (lineNo, line) {
                var items = line.split(',');
                if ((lineNo !== 0) && (line != "")) {
                    var x = new Date(items[0]),
                        speed1 = parseInt(items[1]),
                        speed2 = parseInt(items[2]);

                    var year = x.getFullYear();
                    var month = x.getMonth();
                    var day = x.getDate();
                    var hour = x.getHours();
                    var min = x.getMinutes();
                    var thisDate = Date.UTC(year, month, day, hour, min);


                    speedSeries.push([thisDate, speed1, speed2]);

                }
            });

            options.series.push({
                data: speedSeries,
                type: 'line',
                color: 'DarkBlue'
            });

            var chart = new Highcharts.Chart(options);
        });

如何创建阵列以生成包含两行的图表 - 每个速度类别一个?

1 个答案:

答案 0 :(得分:2)

你需要2个系列才能做到,



var csv = "Timestamp,Speed1,Speed2\n"+
"10/5/2015 12:00:00 AM,86,46.2\n"+
"10/5/2015 1:00:00 AM,78,51\n"+
"10/5/2015 2:00:00 AM,77,52\n"+
"10/5/2015 3:00:00 AM,80,49\n"+
"10/5/2015 4:00:00 AM,112,42\n"+
"10/5/2015 5:00:00 AM,79,50\n";    

var speedSeries = [[],[]];
var lines = csv.trim().split('\n');
$.each(lines, function (lineNo, line) {
  var items = line.split(',');
  if ((lineNo !== 0) && (line != "")) {
    var x = new Date(items[0]),
        speed1 = parseInt(items[1]),
        speed2 = parseInt(items[2]);

    var year = x.getFullYear();
    var month = x.getMonth();
    var day = x.getDate();
    var hour = x.getHours();
    var min = x.getMinutes();
    var thisDate = Date.UTC(year, month, day, hour, min);


    speedSeries[0].push([thisDate, speed1]);
    speedSeries[1].push([thisDate, speed2]);

  }
});

var options = {series:[],chart:{renderTo:"chart"}, xAxis: {type: 'datetime'}};

options.series.push({
  data: speedSeries[0],
  type: 'line',
  color: 'DarkBlue',
  name:"Speed 1"
});
options.series.push({
  data: speedSeries[1],
  type: 'line',
  color: 'Red',
  name:"Speed 2"
});

var chart = new Highcharts.Chart(options);

#chart{
    width: 500px;
    height: 300px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<div id="chart"></div>
&#13;
&#13;
&#13;