问题
I am creating a Google scatter chart. I have one data series which looks something like:
var data = new google.visualization.DataTable();
data.addColumn('number', 'ID');
data.addColumn('number', 'Value');
data.addRows([[1,100], [2,150],
[3,200], [4,250],
[5,300], [6,350],
[7,400], [8,450]]);
I want the colour of the points on the scatter chart to vary, between green and red, based on the 'Value' of each point.
i.e. the colour of point ID=1 should be green, however ID=8 should be red!
Is this possible?
回答1:
Add an extra column to your DataTable, with the role style :
data.addColumn( {'type': 'string', 'role': 'style'} );
Now add styling to each of the rows to get the desired effect :
data.addRows([[1,100, 'point {size: 14; fill-color: green'],
[2,150, 'point {size: 14; fill-color: green'],
....
[8,450, 'point {size: 14; fill-color: red']
]);
demo -> http://jsfiddle.net/v92k8rty/
Update. There is one (out of probably hundreds) javascript library that very easily can provide a gradient palette with customizeable colors and range - RainbowVis-JS. Instead of the above, create a palette by using RainbowVis in the same range as the DataTable, and then add the colors dynamically :
//create a gradient palette from green to red using RainbowVis
var rainbow = new Rainbow();
rainbow.setNumberRange(1, data.getNumberOfRows());
rainbow.setSpectrum('green', 'red');
//alter the DataTable
data.addColumn( {'type': 'string', 'role': 'style'} );
for (var i=0;i<data.getNumberOfRows();i++) {
data.setCell(i, 2, 'point { fill-color:'+rainbow.colorAt(i+1)+'}');
}
demo -> http://jsfiddle.net/ehgfwh8z/
来源:https://stackoverflow.com/questions/31380320/change-point-colour-based-on-value-for-google-scatter-chart