title: D3.js stacked areas with color change above specific value
body: <p>At work someone who isn't available anymore made an application with a <code>D3.js</code> graph in it, it wasn't finished yet and I have to finish it. However I wasn't and I still am not familiar with the D3.js library I could fix some things. But one thing I just can't fix, I have a graph with a colored area, that works and looks well, that has to show a red graph instead of yellow if a value is exceeded. In this case the value is -30, so above the red line (see pictures).</p>
  
  <p>The image on the left shows what I have now and the right one what it needs to be:</p>
  
  <p><img src="https://i.stack.imgur.com/Cn1t8.png" alt="Current graph"> <img src="https://i.stack.imgur.com/cuL6s.png" alt="The solution"></p>
  
  <p>I found out that multiple areas can be stacked with the <a href="https://github.com/mbostock/d3/wiki/Stack-Layout" rel="nofollow noreferrer"><code>d3.layout.stack()</code></a> function. But I only find examples with code using hard-coded <code>JSON</code> or multiple graphs at top of each other.<br>
  The code below is what I have now: (I cut out that is irrelevant)</p>
  
  <pre><code>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");
  });
  </code></pre>
  
  <p>Also, all values below zero should be green colored, but this could be easily extended when having the code for above question. </p>