我有一个数据表,其中包含过去 3 年的汽车销售数量。我想创建一个柱形图,其中每年都有“租赁”、“融资”和“现金销售”列。

我的表格有两列,一列用于销售日期,一列用于销售类型。

到目前为止我已经:

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

这不起作用,我收到错误“TypeError:无法读取未定义的属性“调用””。关于如何让它发挥作用有什么建议吗?

请您参考如下方法:

首先,构建一个 DataView,其中包含每种销售类型的列

然后使用group方法聚合 View

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

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>


评论关闭
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!