How to change the format in the DataTable's Google Chart API with Javascript

北城余情 提交于 2019-12-12 04:57:58

问题


  • I would like to change the format of the data in the DataTable in order to make it more flexible and the Chart is still the same with the first one.

Default:

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

It must be:

['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:


You must transpose array like: 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];
    });
  });
}

Before pass data to arrayToDataTable you mast prepare it in format that google charts will understand.

Transpose – http://en.wikipedia.org/wiki/Transpose

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



来源:https://stackoverflow.com/questions/24281369/how-to-change-the-format-in-the-datatables-google-chart-api-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!