charts - 在堆积条形谷歌图表中显示百分比

标签 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

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

最佳答案

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

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>


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

关于charts - 在堆积条形谷歌图表中显示百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40647885/

相关文章:

javascript - Google 可视化表不会从函数返回

ios - 在 danielgindi/Charts ios 中显示真实的 x 轴值

oracle - 从 Oracle 查询生成图表的选项

javascript - Chart.js:仅在数据点的 x 轴上显示标签

firefox - 谷歌图表 : google is not defined

javascript - googlechart json javascript 的动态数组

algorithm - 给定点的具有精确值的函数插值

google-apps-script - 谷歌应用脚​​本: How to set "Use column A as labels" in chart embedded in spreadsheet?

javascript - 两条垂直线之间的阴影区域

php - 如何使用 mysql 数据库中的数据创建 Google ComboChart?