Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
562 views
in Technique[技术] by (71.8m points)

d3.js - How to customize the color scale in a D3 line chart?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...