d3.js chart area filling with different colors

后端 未结 1 930
心在旅途
心在旅途 2020-12-16 00:26

I\'m attempting to fill the area under the graph with different colors, depending on x value ranges, say for example, for x values 0 to 10 yellow, from 10 to 20 red and so o

相关标签:
1条回答
  • 2020-12-16 01:19

    You basically have two options for doing this.

    • You can define separate areas for the different colours.
    • You can define a single area and use a gradient to simulate different colours.

    The second one is probably easier, as you don't need to draw any separate paths, you can simply fill the one like you're currently doing.

    For the gradient, you would need to define the stops (i.e. colour changes) to correspond to the values. In particular, you would need to introduce two stops at the same place to make it appear like the colour is changing suddenly. More information on gradients here. The code would look something like this.

    var grad = graph.append("defs")
         .append("linearGradient")
         .attr("id", "grad");
    grad.append("stop").attr("offset", "0%").attr("stop-color", "yellow");
    grad.append("stop").attr("offset", "10%").attr("stop-color", "yellow");
    grad.append("stop").attr("offset", "10%").attr("stop-color", "red");
    grad.append("stop").attr("offset", "20%").attr("stop-color", "red");
    // etc
    
    graph.append("path")
         .style("fill", "url(#grad)");
    

    The positions of the stops would be determined by your scale.

    0 讨论(0)
提交回复
热议问题