从CSV读取数据并显示连续图表

时间:2016-02-15 06:01:09

标签: javascript jquery csv highcharts

我正在尝试绘制一个图表,该图表将从csv文件中读取数据,该数据按照以下格式每分钟追加最新数据。

图表将继续从csv文件中读取数据并每隔一秒显示一次图表。你能帮帮我吗?我想显示来自文件的确切时间应该显示在图表上。

CSV格式..

time,count
18:01:00,3
18:01:01,4
....



$(document).ready(function () {
  var csv = [],
      x;

  Highcharts.setOptions({
    global: {
      useUTC: false
    }
  });

  var data = 'time,count\n18:01:00,3\n18:01:01,4';

  //$.get('data.csv', function(data) {
  var lines = data.split('\n');

  $.each(lines, function(lineNo, line) {
    if(lineNo > 0) {
      var items = line.split(',');
      useUTC: false;
      x = items[0].split(':');
      csv.push([Date.UTC(2015,1,1,x[0],x[1],x[2]), parseFloat(items[1])]);
    }
  });

  console.log(csv);

  $('#container').highcharts({
    chart: {
      renderTo: 'container',
      type: 'spline',
      animation: Highcharts.svg, // don't animate in old IE
      marginRight: 10,
      useUTC: false,
      events: {
        load: function () {

          // set up the updating of the chart each second
          var series = this.series[0];

          setInterval(function () {
            var l = series.data.length - 1,
                lastX = series.data[l].x;

            $.get('data.csv', function(data) {
              var lines = data.split('\n'),
                  len = lines.length,
                  items = lines[len - 1].split(','),
                  x = items[0].split(':'),
                  y = parseFloat(items[1]);
              useUTC: false;
              x = Date.UTC(2015,1,1,x[0],x[1],x[2]);

              if(x !== lastX) {
                series.addPoint([x, y], true, true);
              }
            });
          }, 1000); //refresh each 1 second
        }
      }
    },
    title: {
      text: 'TPS Data'
    },
    xAxis: {
      type: 'datetime',
      tickPixelInterval: 150
    },
    yAxis: {
      title: {
        text: 'Value'
      },
      plotLines: [{
        value: 3,
        width: 1,
        color: '#808080'
      }]
    },
    tooltip: {
      formatter: function () {
        return '<b>' + this.series.name + '</b><br/>' +
          Highcharts.dateFormat('%H:%M:%S', this.x) + '<br/>' +
          Highcharts.numberFormat(this.y, 2);
      }
    },
    legend: {
      enabled: false
    },
    exporting: {
      enabled: false
    },


    series: [{
      name: 'Count',
      data: csv
    }]
  });

  //});
});
&#13;
div {
  min-width: 50px;  
  height: 200px; 
  margin: 0 auto;  
}
&#13;
<script type="text/javascript" src="http://code.jquery.com/jquery-1.12.0.js"></script>
<script type="text/javascript" src="http://code.highcharts.com/highcharts.js"></script>
<div id="container" style=""></div>
&#13;
&#13;
&#13;

注意在代码段中,我将ajax函数$.get替换为硬编码数据,以便显示结果,但问题是关于ajax方式。

0 个答案:

没有答案