简体   繁体   中英

D3.js manually creating a diverging color scale? Newbie here

I'm trying to make a visualization, and I'm really getting tripped up on the color scale part. It's kind of laughable how confused this is making me, but lets chalk it up to me being a huge d3 newb...

var colorScale = d3.scaleLinear()
            .domain([-850, -500, -25, 0, 25, 500, 2100])
            .range(["blue", "lightblue", "grey", "white", "grey", "pink", "red"]);
          var labels = ["-850 - -500", '-499 - -25','-24 - 25', '26 - 500', '501 - 2,100'];

Basically I just want to make a range where (-850 to -500) fills the polygon with blue, (-499 to -25) fills with light blue, (-25 to -1) fills with grey, (0) fills with white, (1-25) grey... so on and so forth. I don't want to have colors in between these discrete seven ranges, so scaleLinear is probably wrong--but I think there's a lot wrong here.

I'm not familiar with the different d3.scaleXXX variations, but I have experimented with a few and I'm coming up empty handed. I'm not sure if it's because I'm not using the proper d3.scale function, or if my code/ranges are wonky... Or perhaps a combination of both. Anyway, thanks for the help.

What you're looking for is a threshold scale , which maps values to a discrete range, and map subsets of the domain to these discrete values:

colorScale = d3.scaleThreshold()
            .domain([-850, -500, -25, 0, 25, 500, 2100])
            .range(["none", "blue", "lightblue", "grey", "white", "grey", "pink", "red"]);

Because of how scaleThreshold() works, you need one more value in the range than in your domain to achieve the expected effect. Think of the domain as the thresholds and the range as the values:

none | blue | lightblue | grey | white | grey | pink | red
   -850   -500         -25     0       25    500    2100

In the same vein, you can also use a threshold scale for your labels:

labelScale = d3.scaleThreshold()
                .domain([-850, -500, -25, 25, 500, 2100])
                .range([">850", "-850 - -500", '-499 - -25', '-24 - 25', '26 - 500', '501 - 2,100', '>2,100']);
// labelScale(1000) == '501 - 2,100'

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