如何使用Javascript更改DataTable的Google Chart API中的格式

时间:2014-06-18 09:03:22

标签: javascript charts google-visualization

  • 我想更改DataTable中数据的格式 为了使它更灵活,图表仍然是相同的 第一个。

默认:

['Year', 'Sales', 'Expenses'],
['2004',  1000,      400],
['2005',  1170,      460],
['2006',  660,       1120],
['2007',  1030,      540]

必须是:

['Year', '2004', '2005', '2006', '2007'],
['Sales', 1000, 1170, 660, 1030],
['Expenses', 400 ,460, 1120, 540]

Demo


HTML:

<div id="chart_div" style="width: 450px; height: 300px;"></div>

使用Javascript:

google.load("visualization", "1", {packages:["corechart"]});
  google.setOnLoadCallback(drawChart);
  function drawChart() {
    var data = google.visualization.arrayToDataTable([
      ['Year', 'Sales', 'Expenses'],
      ['2004',  1000,      400],
      ['2005',  1170,      460],
      ['2006',  660,       1120],
      ['2007',  1030,      540]
    ]);

    var options = {
      title: 'Company Performance'
    };

    var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
    chart.draw(data, options);
  }

1 个答案:

答案 0 :(得分:2)

您必须转置数组:http://jsfiddle.net/krzysztof_safjanowski/Mw398/1/

var data = google.visualization.arrayToDataTable(transposeArray([
    ['Year', '2004', '2005', '2006', '2007'],
    ['Sales', 1000, 1170, 660, 1030],
    ['Expenses', 400, 460, 1120, 540]
]));

function transposeArray(array) {
  return array[0].map(function (col, i) {
    return array.map(function (row) {
      return row[i];
    });
  });
}

在将数据传递到arrayToDataTable之前,您需要以谷歌图表理解的格式准备它。

转置 - http://en.wikipedia.org/wiki/Transpose

方法map - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map