d3.js chart area filling with different colors

2020-06-03 04:03发布

问题:

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 on. Is there a way to do that?

My javascript for single fill color is

var m = 80; 
var w = 900 - 3*m;
var h = 600- 3*m; 

var x = d3.scale.linear().range([0, w]);
var y = d3.scale.linear().range([h, 0]);
x.domain(d3.extent(data, function(d) { return d.time; }));
y.domain(d3.extent(data, function(d) { return d.points; }));

var line = d3.svg.line()
.x(function(d) { 
return x(d.time); 
})

.y(function(d) { 
return y(d.points); 
})

var graph = d3.select("#graph").append("svg:svg")
           .attr("width", w+3*m)
           .attr("height", h+3*m)
           .append("svg:g")
           .attr("transform", "translate(" + 1.5*m + "," + 1.5*m + ")");

var area = d3.svg.area()
.x(function(d) { return x(d.time); })
.y0(h)
.y1(function(d) { return y(d.points); });

graph.append("path")
.datum(data)
.attr("class", "area")
.attr("d", area)
.style("fill","steelblue"); 

Thanks in advance!

回答1:

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.