13

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!

user2834030
  • 145
  • 1
  • 5

1 Answers1

12

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.

Pedram Parsian
  • 3,750
  • 3
  • 19
  • 34
Lars Kotthoff
  • 107,425
  • 16
  • 204
  • 204
  • Thanks! This seems to work! But if the number of differently colored areas and stops is variable, depending on the data I plot, how can that be done? – user2834030 Oct 07 '13 at 06:33
  • 1
    Same thing. Everything is added in the code and you can of course use data to define that as well, e.g. `grad.selectAll("stop").data(data).enter()...`. – Lars Kotthoff Oct 07 '13 at 08:24