d3.js chart area filling with different colors

江枫思渺然 提交于 2020-01-01 02:33:28

问题


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.



来源:https://stackoverflow.com/questions/19114896/d3-js-chart-area-filling-with-different-colors

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!