Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to customize the color scale in a D3 line chart?

Tags:

colors

d3.js

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.

like image 491
victorz Avatar asked Jan 18 '14 18:01

victorz


2 Answers

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.

like image 108
Lars Kotthoff Avatar answered Sep 30 '22 02:09

Lars Kotthoff


for D3 v4

   let color = d3.scaleOrdinal()
      .domain(["New York", "San Francisco", "Austin"])
      .range(["#FF0000", "#009933" , "#0000FF"]);
like image 33
Amazingandyyy Avatar answered Sep 30 '22 02:09

Amazingandyyy