Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

conditional fill in d3.js for area chart

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>

like image 525
user1167650 Avatar asked Aug 07 '12 21:08

user1167650


1 Answers

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"); });
like image 167
Lars Kotthoff Avatar answered Sep 23 '22 18:09

Lars Kotthoff