While working on a project, I inherited an application that included a D3.js
graph which needed to be completed. Despite not being familiar with the D3.js library initially, I managed to make some improvements. However, there is one issue I haven't been able to resolve - changing the color of the graph area from yellow to red when a certain value (-30 in this case) is exceeded (refer to the images below).
The image on the left shows the current state while the one on the right depicts the desired outcome:
I learned about stacking multiple areas using the d3.layout.stack()
function. However, most examples I found involved hard-coded JSON or overlaying multiple graphs.
Below is a portion of the existing code (excluding irrelevant parts):
var area = d3.svg.area()
.interpolate("basis")
.x(function (d) {return x(d.date); })
.y0(function (d) {return y(0); })
.y1(function (d) {return y(d.energy); });
var svg = d3.select("#datacontainer2").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom);
svg.append("defs").append("clipPath")
.attr("id", "clip")
.append("rect")
.attr("width", width)
.attr("height", height);
var context = svg.append("g").attr("transform","translate("+margin2.left+","+margin2.top + ")");
d3.csv("file:///data.txt", function (error, data) {
data.forEach(function (d) {
d.date = parseDate(d.date);
d.energy = d.energy;
});
x.domain(d3.extent(data.map(function (d) { return d.date; })));
y.domain([25, -50] /*d3.extent(data.map(function(d) { return d.energy; }))*/ );
x2.domain(x.domain());
y2.domain(y.domain());
focus.append("path")
.datum(data)
.attr("clip-path", "url(#clip)")
.attr("d", area);
// red line
focus.append("svg:line")
.attr("x1", 0)
.attr("x2", height * data.length)
.attr("y1", (function (d) { return y(-30); } ))
.attr("y2", (function (d) { return y(-30); }))
.attr("stroke", "#ff0000")
.attr("stroke-width", "3");
});
Additionally, values below zero should be colored green, a feature that can be easily implemented once the above issue is resolved.