在Google图表上显示独立的X轴系列

时间:2019-04-26 12:11:35

标签: google-chat

我需要在Google图表上显示两个独立的系列。该序列表示相同给定时间范围内的温度和压力,但是采样时间可能不同。下面是我的数据示例

let temperatures = [["Apr 26, 2019, 4:28:28 AM", 25.509],
                    ["Apr 26, 2019, 4:28:38 AM", 26.509],
                    ["Apr 26, 2019, 4:28:48 AM", 25.590],
                    ["Apr 26, 2019, 4:28:58 AM", 25.515],
                    ["Apr 26, 2019, 4:29:08 AM", 24.998]]

let pressures =     [["Apr 26, 2019, 4:28:30 AM", 60.509],
                     ["Apr 26, 2019, 4:28:41 AM", 60.509],
                     ["Apr 26, 2019, 4:28:50 AM", 60.590] 
                     ["Apr 26, 2019, 4:28:57 AM", 60.998]]

有没有办法用这些数据绘制图表?

根据我的理解,ScatterChart和ComboChart都期望相同的x轴值。

1 个答案:

答案 0 :(得分:0)

图表仅期望x轴值在同一列/第一列中。
但是我们可以使用null,其中该系列的x轴值没有值。

我们可以使用Google的join method来合并两个数据集。

var dataTemp = google.visualization.arrayToDataTable(temperatures, true);
var dataPres = google.visualization.arrayToDataTable(pressures, true);
var dataChart = google.visualization.data.join(dataTemp, dataPres, 'full', [[0, 0]], [1], [1]);

和以下选项将压力放置在第二个y轴上。

var options = {
  series: {
    1: {
      targetAxisIndex: 1,
    }
  }
};

请参阅以下工作片段...

google.charts.load('current', {
  packages:['corechart']
}).then(function () {
  let temperatures = [
    ["Apr 26, 2019, 4:28:28 AM", 25.509],
    ["Apr 26, 2019, 4:28:38 AM", 26.509],
    ["Apr 26, 2019, 4:28:48 AM", 25.590],
    ["Apr 26, 2019, 4:28:58 AM", 25.515],
    ["Apr 26, 2019, 4:29:08 AM", 24.998]
  ];

  let pressures = [
    ["Apr 26, 2019, 4:28:30 AM", 60.509],
    ["Apr 26, 2019, 4:28:41 AM", 60.509],
    ["Apr 26, 2019, 4:28:50 AM", 60.590],
    ["Apr 26, 2019, 4:28:57 AM", 60.998]
  ];

  var dataTemp = google.visualization.arrayToDataTable(temperatures, true);
  var dataPres = google.visualization.arrayToDataTable(pressures, true);
  var dataChart = google.visualization.data.join(dataTemp, dataPres, 'full', [[0, 0]], [1], [1]);
  dataChart.setColumnLabel(1, 'Temperature');
  dataChart.setColumnLabel(2, 'Pressure');

  var options = {
    chartArea: {
      height: '100%',
      width: '100%',
      top: 24,
      left: 60,
      right: 16,
      bottom: 100
    },
    height: 400,
    width: '100%',
    series: {
      1: {
        targetAxisIndex: 1,
      }
    }
  };

  var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));
  chart.draw(dataChart, options);
});
<script src='https://www.gstatic.com/charts/loader.js'></script>
<div id='chart_div'></div>