Search code examples
javascriptd3.jscolorbrewer

Combining color schemes for categorical data with linear ranges


I'm creating a grouped bar chart and trying to create a color scale for it.

I see the example here for coloring with a scale. But let's say the bars in the group could be implicitly contained in smaller groups and should have its own linear color scale.

Let's say I wanted in the example linked the first 3 bars of a group on one linear (blue) color scale and the last 4 bars on a different linear (red) color scale. How would I do this?


Solution

  • This is an ad hoc answer, aimed to the example you linked.

    One solution is setting the two scales...

    var scale1 = d3.scaleLinear()
        .range(["lightblue", "darkblue"])
        .domain([0, 2]);
    
    var scale2 = d3.scaleLinear()
        .range(["red", "darkred"])
        .domain([3, 6]);
    

    ... and using the indices to choose which one to use:

    .attr("fill", function(d,i) { return i < 3 ? scale1(i) : scale2(i)});
    

    Note that I'm using the domains to match the bars:

    .domain([0, 2])//goes from the first to the third bar
    .domain([3, 6])//goes from the forth to the seventh bar
    

    Here is the updated bl.ocks: https://bl.ocks.org/anonymous/5ba7ad96872b4b5bbc2d212b2ca6e9d0/20e1ed6bb00484f736eab4cad8c221e83bea63d2