显示堆积条形Google图表中的百分比

时间:2016-11-17 06:14:43

标签: charts google-visualization

// Display google stacked bar chart
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
    calc: "stringify",
    sourceColumn: 1,
    type: "string",
role: "annotation"
},
2]);

下面是我拥有的bar chart堆叠的图片。

enter image description here

我无法在绿色栏上显示百分比,但不能在红色栏上显示。 绿色条中的当前值不是百分比值。

1 个答案:

答案 0 :(得分:3)

每个系列都需要一个注释列...

var view = new google.visualization.DataView(data);
view.setColumns([0,
  // series 0
  1, {
    calc: "stringify",
    sourceColumn: 1,
    type: "string",
    role: "annotation"
  },
  // series 1
  2, {
    calc: "stringify",
    sourceColumn: 2,
    type: "string",
    role: "annotation"
  }
]);

编辑

将注释值格式化为百分比

用自定义函数替换"stringify"函数

使用NumberFormat formatter格式化值

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



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

function drawSeriesChart() {
  var data = new google.visualization.DataTable();
  data.addColumn('string', 'Month');
  data.addColumn('number', 'Category A');
  data.addColumn('number', 'Category B');
  data.addRows([
    ['Sep', 100, 190],
    ['Oct', 220, 178]
  ]);

  var formatPercent = new google.visualization.NumberFormat({
    pattern: '#,##0.0%'
  });
  
  var view = new google.visualization.DataView(data);
  view.setColumns([0,
    // series 0
    1, {
      calc: function (dt, row) {
        return dt.getValue(row, 1) + ' (' + formatPercent.formatValue(dt.getValue(row, 1) / (dt.getValue(row, 1) + dt.getValue(row, 2))) + ')';
      },
      type: "string",
      role: "annotation"
    },
    // series 1
    2, {
      calc: function (dt, row) {
        return dt.getValue(row, 2) + ' (' + formatPercent.formatValue(dt.getValue(row, 2) / (dt.getValue(row, 1) + dt.getValue(row, 2))) + ')';
      },
      type: "string",
      role: "annotation"
    }
  ]);

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

<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
&#13;
&#13;
&#13;

更新的屏幕截图 For reference to my COMMENT