简体   繁体   中英

How to set up custom color scale with multiple sub-parts in D3?

I' trying to set up a custom colorScale for my legend. The Result should look like this:

自定义色标

Due to the smooth Transitions it probably should be a d3.scaleLinear() but no matter what I try I can't figure out the way. I've tried d3.scaleThreshold() which at least seem to differentiate the domain-parts well enough.

var colorScale = d3.scaleThreshold()
                   .domain([20,35,50])
                   .range( ["#3AAA35", "#FCEA10", "#F39200", "#E30613", "#582123"] );

This seems to produce the best output right now, as in: each part gets its discrete color to the threshold.

I've tried something like this, but that did also not work at all:

.range([ d3.interpolateRgb("#3AAA35", "#FCEA10")),
         d3.interpolateRgb("#FCEA10", "#F39200"),
         d3.interpolateRgb("#F39200", "#E30613"),
         d3.interpolateRgb("#E30613", "#582123")]); 

This looks simple, but I can't figure it out.

Just as a threshold scale, you can use more than 2 values in the linear scale range and domain, creating a piecewise scale:

const colorScale = d3.scaleLinear()
  .domain([0, 20, 35, 50, 100])
  .range(["#3AAA35", "#FCEA10", "#F39200", "#E30613", "#582123"]);

This is the result:

 const colorScale = d3.scaleLinear() .domain([0, 20, 35, 50, 100]) .range(["#3AAA35", "#FCEA10", "#F39200", "#E30613", "#582123"]); const w = 550, h = 40; const canvas = d3.select("body") .append("canvas") .attr("width", w) .attr("height", h); const context = canvas.node().getContext("2d"); for (let i = 0; i < w; i++) { context.fillStyle = colorScale(i / (w / 100)) context.fillRect(i, 0, 1, h); };
 <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM