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

Sky*_*obs 5 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]);
Run Code Online (Sandbox Code Playgroud)

下面是我的堆积条形图的图片。

在此输入图像描述

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

Whi*_*Hat 4

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

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"
  }
]);
Run Code Online (Sandbox Code Playgroud)

编辑

将注释值格式化为百分比

将函数替换"stringify"为自定义函数

使用NumberFormat格式化程序来格式化值

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

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"
  }
]);
Run Code Online (Sandbox Code Playgroud)
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'
  });
}
Run Code Online (Sandbox Code Playgroud)

更新的屏幕截图 供参考我的评论