Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change point colour based on value for Google Scatter Chart

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?

like image 835
AnPocArBuile Avatar asked Jul 13 '15 09:07

AnPocArBuile


People also ask

How do I change the color of one point in a scatter graph?

On a chart, select the individual data marker that you want to change. On the Format tab, in the Shape Styles group, click Shape Fill. Do one of the following: To use a different fill color, under Theme Colors or Standard Colors, click the color that you want to use.


1 Answers

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)+'}');
}    

enter image description here demo -> http://jsfiddle.net/ehgfwh8z/

like image 53
davidkonrad Avatar answered Sep 28 '22 11:09

davidkonrad