Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

d3.js chart area filling with different colors

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!

like image 766
user2834030 Avatar asked Oct 01 '13 11:10

user2834030


1 Answers

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.

like image 70
Lars Kotthoff Avatar answered Sep 20 '22 18:09

Lars Kotthoff