【问题标题】:Plotting multiple series from JSON php import to Highcharts绘制从 JSON php 导入到 Highcharts 的多个系列
【发布时间】:2016-08-14 18:37:44
【问题描述】:

因为我对 JS 很陌生,所以我不明白如何在我的代码中实现多个数据系列

这是我用作数据采集器的 php 页面:

getTrendData-TIMEREQUESTED-hms.php

<?php
    //Define possible Argument request
    $format = $_GET['format'];

    if($format=='json')    {
        header("Content-type: text/json");
    }

    //Define database credential
    $servername = "localhost";
    $username   = "test";
    $password   = "test";
    $dbname     = "test";
    try {
        //Open connection to mysql_db from defined Database credentials
        $connection = mysqli_connect($servername, $username, $password, $dbname) or die ("Error " . mysqli_error($connection));
        $sql   = "select TIMEREQUESTED,TS FROM TIMEREQUESTED ORDER BY TS;";
        $result = mysqli_query($connection, $sql) or die ("Error in Selecting " . mysqli_error($connection));
        //create an array
        $data = array();
        while($row = mysqli_fetch_assoc($result))    {
            $TIMEREQUESTED = strtotime($row['TIMEREQUESTED'])*1000;
            $TS = strtotime($row['TS'])*1000;
            $data[] = array($TS, $TIMEREQUESTED);
        }

        echo json_encode($data);
        //close the db connection
        mysqli_close($connection);
    }

    catch(PDOException $e)  {
        echo $e->getMessage();
    }

    ?>

比我在 HighCharts 中包含一个 Ajax 调用,每 2500 毫秒调用一次,

getTrendData-TIMEREQUESTED-hms.php

[[1461241983000,5.67,0],[1461242015000,16.67,0],[1461242164000,16.67,0],[1461242303000,26.25,0],[1461242835000,-2.5,0],[1461242869000,-2.5,0],[1461242991000,1.5,0],[1461243034000,3.14,0],[1461243374000,-14.22,0],[1461243456000,-11.92,0],[1461244995000,0,0],[1461245036000,-3.6,140],[1461245208000,-3,140],[1461245260000,3.56,140],[1461245312000,2.1,140],[1461245346000,2.1,140],[1461245411000,3.5,140],[1461245442000,3.5,140],[1461245479000,-1,140],[1461245757000,-0.8,140],[1461245809000,-0.69,140]]

TIMEREQUESTED-hms.html

function buildTIMEREQUESTED() {
  var chart;
  var dataSource = 'getTrendData-TIMEREQUESTED-hms.php?format=json';
  var ChartHeight = window.innerHeight;

  function requestData() {
    $.ajax({
      url: dataSource,
      success: function(points) {
        chart.series[0].setData(points, true);
        setTimeout(requestData, 2500);
      },
      cache: false
    });
  }
  $(document).ready(function() {
    //add our div for the chart
    $("#container").append("<div id=chart-laptime style='width:100%''></div>");
    chart = new Highcharts.Chart({
      chart: {
        height: ChartHeight,
        renderTo: 'chart-laptime',
        defaultSeriesType: 'line',
        events: {
          load: function() {
            requestData();
          }
        },
      },
      tooltip: {
        enabled: true,
        formatter: function() {
          s = (this.y / 1000);
          m = Math.floor(s / 60);
          h = Math.floor(m / 60);
          s = s % 60;
          m = m % 60;
          h = h % 24;
          if (h < 9) h = "0" + h;
          if (m < 9) m = "0" + m;
          if (s < 9) s = "0" + s;
          return '<span style="color:black">Time Zero - </span>' + [m, s].join(':');
        }
      },
      title: {
        text: 'TIMEREQUESTED'
      },
      subtitle: {
        text: 'BEST 5 CAR AVEREGE LAPTIME IN LAST 10 MINUTES'
      },
      xAxis: {
        type: 'datetime',
        title: {
          text: 'RACE TIME'
        }
      },
      yAxis: {
        type: 'datetime',
        dateTimeLabelFormats: {
          millisecond: '%H:%M:%S',
        },
        //dateFormat: {"%H:%M:%S.%L"}
        title: {
          text: 'TIMEREQUESTED'
        }
      },
      series: [{
        name: 'TIMEREQUESTED',
        showInLegend: false,
        //tooltip: {type: 'datetime',},
        data: [],
      }]
    }); //end chart               
  }); //end document.ready
}

这样我可以正确显示单个系列,但是通过 MySQL 查询,我可以从数据库中获取更多列,并解析 json 文件的每一行,(如 JSON 文件中所示来自 php 请求,每个数组都有第三个值)但我无法理解如何显示多个数据系列,xAxis 上始终是 JSON 文件的第一列,而 yAxis 上每次都有不同的列.

您能给我一些关于如何在同一个图表上显示多个系列的建议吗?不胜感激,

最好的问候。

【问题讨论】:

  • 先有个疑问,[1461241983000,5.67,0]数据格式,第一个值是时间戳,第二个和第三个值是什么?两个系列的 y 轴值?
  • 是的,它们是两个系列的 y 轴值
  • 所以对于两个不同的系列,您需要不同的数组。所以对于一个系列[1461241983000,5.67] 和第二个系列[1461241983000,0]。然后为两个不同的系列调用setData 而不仅仅是chart.series[0]
  • 我可以在“function(points) {}”中使用 javascript 创建所有数组吗?如果有人可以提供一些示例代码将不胜感激。

标签: php mysql json highcharts


【解决方案1】:
var dataForTwoSeries = [[1461241983000,5.67,0],[1461242015000,16.67,0],[1461242164000,16.67,0]]; //your data, just took 3 elements. Should work for any number of elements.
var seriesOne = [];
var seriesTwo = [];
$.each(dataForTwoSeries, function(index, dataPoints){
   var seriesOneDataPoint = [dataPoints[0], dataPoints[1]];
   var seriesTwoDataPoint = [dataPoints[0], dataPoints[2]];

   seriesOne.push(seriesOneDataPoint);
   seriesTwo.push(seriesTwoDataPoint);
});

然后您必须在图表对象中创建 2 个系列,例如

series: [{
    name: 'seriesName1',
    showInLegend: false,
    data: [],
},{
    name: 'seriesName2',
    showInLegend: false,
    data: [],
}]

并在您的 requestData 方法中,为两者设置数据

chart.series[0].setData(seriesOne, false); //redraw after setting data for second series
chart.series[1].setData(seriesTwo); //boolean redraw is true by default, don't need to pass it

编辑:更新代码后,这些是您进一步需要进行的更改。

$.ajax({url: dataSource, success: function(dataForTwoSeries) //dataForTwoSeries is the data you get from the request 
  {
  //var dataForTwoSeries = []; you don't need this.
  var seriesOne = []; //these two don't have to be global.
  var seriesTwo = [];
  $.each(dataForTwoSeries, function(index, dataPoints){

    var seriesOneDataPoint = [dataPoints[1], dataPoints[0]];
    var seriesTwoDataPoint = [dataPoints[2], dataPoints[0]];

    seriesOne.push(seriesOneDataPoint);
    seriesTwo.push(seriesTwoDataPoint);
  }); // draw chart after iteration and not during each interation
    chart.series[0].setData(seriesOne, false); //redraw after setting data for second series
    chart.series[1].setData(seriesTwo); //boolean redraw is true by default, don't need to pass it

    setTimeout(requestData, 2500);

  },
  cache: false
  });

【讨论】:

  • 非常感谢,我正在测试代码,但我遇到了一些语法错误......一旦我摆脱它们,我会给出反馈
  • 我在第一行之后缺少了一个分号。我不知道这是否是您遇到语法错误的地方。
  • 我已经更新了上面答案中的代码,现在没有语法错误,但我没有显示数据。我要放一些 windows.allert() 让你了解数据流在哪里中断。
  • 现在它就像一个魅力,实际上图表在每次迭代中都以令人印象深刻的缓慢重新绘制。非常感谢您提供的所有建议以及提供的代码,非常感谢。
【解决方案2】:

我已经更新了代码,现在没有语法错误,但我没有显示任何数据。我将放置一些 windows.allert() 以便了解数据流中断的位置。

这是更新后的代码:

<!DOCTYPE html>
<html>
<head>
    <title>Strategy - Time Zero</title>
    <script src="js/jquery/jquery-1.12.3.js"></script>
    <link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <script src="js/Highcharts/Highcharts-4.2.3/highcharts.js"></script>
    <script src="js/Highcharts/Highcharts-4.2.3/modules/exporting.js"></script>
    <script>

  var chart;
  var dataSource = 'getTrendData-TimeZero.php?format=json';
  var ChartHeight = window.innerHeight;
  var dataForTwoSeries = [];
  var seriesOne = [];
  var seriesTwo = [];

  function requestData() {

    $.ajax({url: dataSource, success: function(dataPoints) 
      {
      $.each(dataForTwoSeries, function(index, dataPoints){

        var seriesOneDataPoint = [dataPoints[1], dataPoints[0]];
        var seriesTwoDataPoint = [dataPoints[2], dataPoints[0]];
        window.alert(seriesOneDataPoint)

        seriesOne.push(seriesOneDataPoint);
        seriesTwo.push(seriesTwoDataPoint);

        chart.series[0].setData(seriesOne, false); //redraw after setting data for second series
        chart.series[1].setData(seriesTwo); //boolean redraw is true by default, don't need to pass it

        setTimeout(requestData, 2500);
      });
      },
      cache: false
      });


  }
  $(document).ready(function() {
    //add our div for the chart
    $("#container").append("<div id=chart-TimeZero style='width:100%''></div>");
    //StockChart
    //Chart
    chart = new Highcharts.Chart({
      chart: {
        height: ChartHeight,
        renderTo: 'chart-TimeZero',
        defaultSeriesType: 'line',
        events: {
          load: function() {
            requestData();
          }
        },
      },
      tooltip: {
        enabled: true,
        formatter: function() {
          if (this.y < 0) 
          {
          h = Math.ceil(this.y / 3600);
          m = Math.ceil(this.y / 60);
          s = Math.ceil(this.y % 60);
          h = Math.abs(h);
          m = Math.abs(m);
          s = Math.abs(s);
          s = s % 60;
          m = m % 60;
          h = h % 24;
          if (h < 9) h = "-0" + h;
          if (m < 9) m = "0" + m;
          if (s < 9) s = "0" + s;
          }
          else
          {
          h = Math.floor(this.y / 3600);
          m = Math.floor(this.y / 60);
          s = Math.floor(this.y % 60);
          h = Math.abs(h);
          m = Math.abs(m);
          s = Math.abs(s);
          s = s % 60;
          m = m % 60;
          h = h % 24;
          if (h < 9) h = "0" + h;
          if (m < 9) m = "0" + m;
          if (s < 9) s = "0" + s;
          }
          return '<span style="color:black">Time Zero</span> ' + [h, m, s].join(':');
        }
      },
      title: {
        text: 'TIME ZERO'
      },
      subtitle: {
        text: 'BEST 5 CAR AVEREGE LAPTIME IN LAST 10 MINUTES'
      },
      xAxis: {
        type: 'datetime',
        title: {text: 'DAY TIME'}
      },
          yAxis: {
        title: {text: 'TIME ZERO'},
        labels: {                
        formatter: function() {
          if (this.value < 0) 
          {
          h = Math.ceil(this.value / 3600);
          m = Math.ceil(this.value / 60);
          s = Math.ceil(this.value % 60);
          h = Math.abs(h);
          m = Math.abs(m);
          s = Math.abs(s);
          s = s % 60;
          m = m % 60;
          h = h % 24;
          if (h < 9) h = "-0" + h;
          if (m < 9) m = "0" + m;
          if (s < 9) s = "0" + s;
          }
          else
          {
          h = Math.floor(this.value / 3600);
          m = Math.floor(this.value / 60);
          s = Math.floor(this.value % 60);
          h = Math.abs(h);
          m = Math.abs(m);
          s = Math.abs(s);
          s = s % 60;
          m = m % 60;
          h = h % 24;
          if (h < 9) h = "0" + h;
          if (m < 9) m = "0" + m;
          if (s < 9) s = "0" + s;
          }
          return [h, m, s].join(':');
        }
        }
    },
series: [{
    name: 'seriesName1',
    showInLegend: true,
    data: [],
},{
    name: 'seriesName2',
    showInLegend: true,
    data: [],
}]
    }); //end chart       
  }); //end document.ready

</script>
</head>
<body>
    <div id="container"></div>
</body>
</html>

【讨论】:

  • 抱歉,我的代码中出现复制粘贴错误。更正了它。另外,我不知道您的 ajax 调用在没有 url 的情况下是否有效。当您发出 ajax 请求时,您会得到 [[1461241983000,5.67,0],[1461242015000,16.67,0],[1461242164000,16.67,0]] 这对吗?然后使用 url 和成功回调函数进行正确的 ajax 调用。将返回的对象名称重命名为 dataForTwoSeries 并将 $.each 块放在回调中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-23
  • 1970-01-01
  • 2014-06-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多