我正在尝试将 Google 图表中的单元格格式设置为百分比字段。
对于它适用的列:
var flow_format2 = new google.visualization.NumberFormat( {suffix: '%', negativeColor: 'red', negativeParens: true, fractionDigits: 0} );
但据我所知,不可能有一行,因此我想在单元格级别上执行此操作 - 这可能吗?
是否需要使用setProperty
来完成它以及格式化语法是什么。
最佳答案
您可以使用formatValue
方法 NumberFormat
获取格式化字符串
而不是应用于整个列
然后你可以手动setFormattedValue
在数据表单元格上
要更改颜色,请使用 setProperty
更改单元格的 'style'
属性(property)
图表必须在之后绘制
--或--
当图表的 'ready'
事件触发后,您可以使用 DOM 更改单元格值
Table
图表生成一组正常的 html <table>
标签
以下是一个工作片段,演示了这两种方法...
google.charts.load('current', {
callback: function () {
var dataTable = new google.visualization.DataTable({
cols: [
{label: 'Name', type: 'string'},
{label: 'Amount', type: 'number'},
],
rows: [
{c:[{v: 'Adam'}, {v: -1201}]},
{c:[{v: 'Mike'}, {v: 2235}]},
{c:[{v: 'Stephen'}, {v: -5222}]},
{c:[{v: 'Victor'}, {v: 1288}]},
{c:[{v: 'Wes'}, {v: -6753}]}
]
});
var container = document.getElementById('chart_div');
var tableChart = new google.visualization.Table(container);
var patternFormat = {
suffix: '%',
negativeColor: '#FF0000',
negativeParens: true,
fractionDigits: 0
};
// create the formatter
var formatter = new google.visualization.NumberFormat(patternFormat);
// format cell - first row
dataTable.setFormattedValue(0, 1, formatter.formatValue(dataTable.getValue(0, 1)));
if (dataTable.getValue(0, 1) < 0) {
dataTable.setProperty(0, 1, 'style', 'color: ' + patternFormat.negativeColor + ';');
}
google.visualization.events.addOneTimeListener(tableChart, 'ready', function () {
// format cell via DOM - third row
var tableCell = container.getElementsByTagName('TR')[3].cells[1];
tableCell.innerHTML = formatter.formatValue(dataTable.getValue(2, 1));
if (dataTable.getValue(2, 1) < 0) {
tableCell.style.color = patternFormat.negativeColor;
}
});
tableChart.draw(dataTable, {
allowHtml: true
});
},
packages: ['table']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
关于charts - Google 图表表格将单元格格式设置为百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38264974/