如何使用不同的x轴值绘制Google折线图

时间:2017-03-02 08:10:35

标签: javascript charts google-visualization

有两个这样的值:

var company1 = [
    [new Date(2004, 12, 1), 1000],
    [new Date(2004, 12, 3), 500],
    [new Date(2004, 12, 7), 950]
    [new Date(2004, 12, 8), 1000]];
var company2 = [
    [new Date(2004, 12, 2), 800],
    [new Date(2004, 12, 4), 600],
    [new Date(2004, 12, 5), 300]
    [new Date(2004, 12, 8), 500]];

我想绘制这样的图表。

enter image description here

要绘制这样的折线图,我是否需要创建这样的数组?

  ['2004/12/1', 1000, null],
  ['2004/12/2', 750, 800],
  ['2004/12/3', 500, 700],
  ['2004/12/4', 650, 600],
  ['2004/12/5', 800, 300],
  ['2004/12/7', 950, 400],
  ['2004/12/8', 1000, 500]

或者是否有更简单的方法来创建具有不同x轴值的图表?

这是图表的jsfiddle代码段。 https://jsfiddle.net/fe26/u3n8qsay/

1 个答案:

答案 0 :(得分:1)

您可以使用google_visualization_data_join加入两组数据。见Google Chart - two date series on the same chart

google.charts.load('current', {'packages': ['corechart']});
google.charts.setOnLoadCallback(drawChart);

function drawChart() {
    var data1 = new google.visualization.DataTable();
    data1.addColumn('date', 'Date');
    data1.addColumn('number', 'Company 1');
    
    data1.addRows([
      [new Date(2004, 11, 1), 1000],
      [new Date(2004, 11, 3), 500],
      [new Date(2004, 11, 7), 950],
      [new Date(2004, 11, 8), 1000]
    ]);
    
    var data2 = new google.visualization.DataTable();
    data2.addColumn('date', 'Date');
    data2.addColumn('number', 'Company 2');
    
    data2.addRows([
      [new Date(2004, 11, 2), 800],
      [new Date(2004, 11, 4), 600],
      [new Date(2004, 11, 5), 300],
      [new Date(2004, 11, 8), 500]
    ]);
    
    var joinedData = google.visualization.data.join(data1, data2, 'full', [[0, 0]], [1], [1]);
    
    var chart = new google.visualization.LineChart(document.querySelector('#chart_div'));
    chart.draw(joinedData, {
        height: 300,
        width: 600,
        interpolateNulls: true
    });
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>