在Google柱形图中按年份汇总类别

时间:2017-01-21 00:04:13

标签: javascript charts google-visualization

我有一个数据表,显示过去3年的汽车销售数量。我想创建一个柱形图,其中包含"租赁"," financed"和"现金销售"在每一年。

我的表有两列,一列是销售日期,另一列是销售类型。

到目前为止,我有:

var groupedData = google.visualization.data.group(
    googleDataTable,
    [ { column: 0, modifier: getYearForRow, type: 'string', label: 'Year'} ],
    [ { column: 1, type: 'string', label: 'Type'} ] );

这不起作用,我收到错误" TypeError:无法读取属性' call'未定义"。关于如何让它发挥作用的任何建议?

1 个答案:

答案 0 :(得分:1)

首先,为每个销售类型

构建一个包含列的DataView

然后使用group方法聚合视图

请参阅以下工作代码段...

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

function drawChart() {
  var data = google.visualization.arrayToDataTable([
    ['Sale Date', 'Sale Type'],
    [new Date(2016, 0, 16), 'cash sale'],
    [new Date(2016, 0, 16), 'cash sale'],
    [new Date(2016, 0, 16), 'leased'],
    [new Date(2016, 0, 16), 'leased'],
    [new Date(2016, 0, 16), 'financed'],
    [new Date(2017, 0, 16), 'cash sale'],
    [new Date(2017, 0, 16), 'cash sale'],
    [new Date(2017, 0, 16), 'cash sale'],
    [new Date(2017, 0, 16), 'financed'],
    [new Date(2016, 0, 17), 'cash sale'],
    [new Date(2016, 0, 17), 'financed'],
    [new Date(2016, 0, 17), 'cash sale'],
    [new Date(2016, 0, 17), 'leased'],
    [new Date(2016, 0, 17), 'financed'],
    [new Date(2017, 0, 17), 'financed'],
    [new Date(2017, 0, 17), 'financed'],
    [new Date(2017, 0, 17), 'cash sale'],
    [new Date(2017, 0, 17), 'financed'],
    [new Date(2016, 0, 18), 'leased'],
    [new Date(2016, 0, 18), 'cash sale'],
    [new Date(2017, 0, 18), 'cash sale'],
    [new Date(2017, 0, 18), 'cash sale']
  ]);

  // build view and aggregation columns
  var viewColumns = [{
    label: 'year',
    type: 'string',
    calc: function (dt, row) {
      return dt.getValue(row, 0).getFullYear().toString();
    }
  }];
  var aggColumns = [];
  var saleTypes = data.getDistinctValues(1);
  saleTypes.forEach(function (saleType) {
    var colIndex = viewColumns.push({
      label: saleType,
      type: 'number',
      calc: function (dt, row) {
        return (dt.getValue(row, 1) === saleType) ? 1 : 0;
      }
    });
    aggColumns.push({
      aggregation: google.visualization.data.sum,
      column: colIndex - 1,
      label: saleType,
      type: 'number'
    });
  });

  var view = new google.visualization.DataView(data);
  view.setColumns(viewColumns);

  var summary = google.visualization.data.group(
    view,
    [0],
    aggColumns
  );

  var container = document.body.appendChild(document.createElement('div'));
  var chart = new google.visualization.ColumnChart(container);
  chart.draw(summary, {
    legend: {
      position: 'top'
    }
  });
}
<script src="https://www.gstatic.com/charts/loader.js"></script>