问题
I want to be able to conditionally set a color for a given column in a google graphs column chart depending on its value. for example, if the bar is <50, color it yellow or higher than 70, color it green. It would be great if the solution be accomplished within the API itself but that's probably not going to be the case.
回答1:
you can use a 'style' column role to color specific columns
the style role is just a column in the data table,
that should follow the series column it should style
if you wanted to color a column green for example...
['A', 100, 'green']
to assign a color conditionally,
we can use a DataView, and the setColumns method
which allows us to add a calculated column
see following working snippet,
an array is used to store the value ranges, and the associated color...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['x', 'y'],
['A', 9],
['B', 30],
['C', 50],
['D', 70],
['E', 90]
]);
var ranges = [
[0, 10, '#e53935'], // red
[10, 50, '#fdd835'], // yellow
[50, 90, '#43a047'], // green
[90, null, '#1e88e5'] // blue
];
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc: function (dt, row) {
var rowValue = dt.getValue(row, 1);
var color;
ranges.forEach(function (range, index) {
if ((rowValue >= range[0]) && ((rowValue < range[1]) || (range[1] === null))) {
color = range[2];
}
});
return color;
},
role: 'style',
type: 'string'
}]);
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(view, {
legend: 'none'
});
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
来源:https://stackoverflow.com/questions/46596229/google-column-graphs-set-color-conditionally