如何绘制堆积图类型的Google图表 [英] How to draw Google Charts of type stacked columns

查看:70
本文介绍了如何绘制堆积图类型的Google图表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个表结构:

Name Grade       Count
X    VeryGood      10
X    Excellent      2
X    Failed         0
Y    VeryGood       7
Y    Excellent      1
Y    Failed         2

我想在堆积的goole图表中显示与此类似的数据:

I want to show this data in stacked goole chart similar to this:

水平地:计数

垂直:名称

任何想法我该如何实现? 附注:我正在使用ajax数据源.

Any ideas how can I achieve that? P.S: I am using ajax data source.

推荐答案

要绘制有问题的图表,数据表的结构需要如下,
每个等级都有系列/列.

to draw the chart in question, the data table will need to be structured as follows,
with series / columns for each grade.

['Name', 'VeryGood', 'Excellent', 'Failed'],
['X', 10, 2, 0],
['Y', 7, 1, 2],

但这很难建立,
无需对查询中的列值进行硬编码.

but this will be difficult to build,
without hard-coding the column values in the query.

相反,我们可以使用Google的DataViewgroup方法.

instead, we can use google's DataView and group method.

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

see following working snippet...

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {
  var data = google.visualization.arrayToDataTable([
    ['Name', 'Grade', 'Count'],
    ['X', 'VeryGood', 10],
    ['X', 'Excellent', 2],
    ['X', 'Failed', 0],
    ['Y', 'VeryGood', 7],
    ['Y', 'Excellent', 1],
    ['Y', 'Failed', 2],
  ]);

  var aggColumns = [];
  var viewColumns = [0];

  var distinctLabels = data.getDistinctValues(1);
  distinctLabels.forEach(function (label, index) {
    viewColumns.push({
      calc: function (dt, row) {
        if (dt.getValue(row, 1) === label) {
          return dt.getValue(row, 2);
        }
        return null;
      },
      type: 'number',
      label: label
    });
    aggColumns.push({
      column: index + 1,
      aggregation: google.visualization.data.sum,
      type: 'number'
    });
  });

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

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

  var chart = new google.visualization.BarChart(document.getElementById('chart'));
  chart.draw(groupData, {
    isStacked: true
  });
});

<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart"></div>

这篇关于如何绘制堆积图类型的Google图表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆