I have an area graph (supposed to represent a time series). I want to color the graph based on the y value such that for regions where the y > c it is one color and for the area where y<=c it is another color. Is this possible in D3?
This is the code I have that generates a single color graph:
var width = 700,
height = 400;
var vis = d3.select("#chart")
.append("svg")
.attr("width",width)
.attr("height",height);
var mpts = [{"x":0,"val":15}];
var n = 200;
for(var i=0;i<n;i++)
{
if(Math.random()>.5)
{
mpts = mpts.concat({"x":i+1,"val":mpts[i].val*(1.01)});
}
else
{
mpts = mpts.concat({"x":i+1,"val":mpts[i].val*(.99)});
}
}
var x = d3.scale.linear().domain([0,n]).range([10,10+width]);
var y = d3.scale.linear().domain([10,20]).range([height-10,0]);
var area = d3.svg.area()
.interpolate("linear")
.x(function(d) { return x(d.x); })
.y1(function(d) { return y(d.val); })
.y0(function(d) { return y(0); });
vis.append("svg:path")
.attr("class", "area")
.attr("d",area(mpts))
.attr("fill","orange");
</script>
Change the way you add the areas to something like
vis.selectAll("path").data(mpts).enter().append("svg:path")
.attr("class", "area")
.attr("d", area)
.attr("fill", function(d) { return (d.val > c ? "orange" : "yellow"); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With