问题
Google Visualization's formatter can be called on a specific column, but not on a particular row.
I want to color code by the row, where each entry per row has a specific condition to meet. How can I achieve that?
Call formatter.format(table, colIndex), passing in the DataTable and the >(zero-based) column number of the data to reformat.
Link to Docs
回答1:
along with the options in this answer,
Google table Chart : how do I change the row background color based on a value,
you can set properties on the data table cell.
the table chart will accept cell properties for both style
and className
when using object notation to load the data, use the p:
key to set properties.
{v: 'Web', f: null, p: {style: 'background-color: cyan;'}}
where v:
= value, f:
= formatted value, & p:
= cell properties
to set the properties after the data has been loaded,
you can use any of the following methods.
1) setCell(rowIndex, columnIndex, value, formattedValue, properties)
when using setCell
, properties is the 5th argument, pass an object with the properties you want to set, e.g.
data.setCell(0, 0, 'Shoes', null, {style: 'background-color: yellow;'});
2) setProperty(rowIndex, columnIndex, name, value)
when using setProperty
, pass the name and value of the property you want to set, e.g.
data.setProperty(1, 0, 'style', 'background-color: lime;');
3) setProperties(rowIndex, columnIndex, properties)
when using setProperties
, pass an object with the properties you want to set, e.g.
data.setProperties(2, 1, {style: 'background-color: magenta;'});
see following working snippet for examples...
google.charts.load('current', {
packages: ['table']
}).then(function () {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Department');
data.addColumn('number', 'Revenues');
data.addRows([
['Shoes', 10700],
['Sports', -15400],
['Toys', 12500],
['Electronics', -2100],
['Food', 22600],
['Art', 1100],
[
// add style property
{v: 'Web', p: {style: 'background-color: cyan;'}},
{v: 9999, p: {style: 'background-color: cyan;'}}
]
]);
// use setCell(rowIndex, columnIndex [, value [, formattedValue [, properties]]])
data.setCell(0, 0, 'Shoes', null, {style: 'background-color: yellow;'});
// use setProperty(rowIndex, columnIndex, name, value)
data.setProperty(1, 0, 'style', 'background-color: lime;');
// use setProperties(rowIndex, columnIndex, properties)
data.setProperties(2, 1, {style: 'background-color: magenta;'});
// use a css className instead of style
data.setProperty(3, 0, 'className', 'customCell');
var container = document.getElementById('table_div');
var table = new google.visualization.Table(container);
table.draw(data, {
allowHtml: true
});
});
.customCell {
color: red;
font-weight: bold;
text-decoration: underline;
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="table_div"></div>
来源:https://stackoverflow.com/questions/56260829/use-google-visualiztion-formatter-on-rows-rather-than-columns