How do I change the color of lines in a d3 line chart, for example in Mike Bostock's multi-series D3 line chart.
In his example chart, Mike Bostock uses D3's built-in "category10" color scale, as per this line of code:
var color = d3.scale.category10();
But suppose, instead of the built-in scale, we wanted the line for Austin to be blue, the line for New York to be red, and the line for San Francisco to be green. Should be simple enough, right? Just define a custom color scale:
var color = d3.scale.ordinal()
.domain(["New York", "San Francisco", "Austin"])
.range("#FF0000", "#009933" , "#0000FF");
I thought that might do the trick – but it turns all the series black. I've tried CSS styling each series by appending classes to them, but that didn't work.
You're only missing the square brackets around the values in .range()
-- it takes an array as argument. So the code should be
var color = d3.scaleOrdinal() // D3 Version 4
.domain(["New York", "San Francisco", "Austin"])
.range(["#FF0000", "#009933" , "#0000FF"]);
Complete example here.
for D3 v4
let color = d3.scaleOrdinal()
.domain(["New York", "San Francisco", "Austin"])
.range(["#FF0000", "#009933" , "#0000FF"]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With