Rahi
Rahi

Reputation: 347

D3.js chart call and re-plot area after zoomed

I am pretty new to d3.js. I have made multi-line chart using some data and chart have zoom functionality, which works pretty fine. Now i wanted to shade area below bottom line, which I did using below code:-

var area = d3.svg.area()
    .x(function(d) { return x(d.x); })
    .y0(height)
    .y1(function(d) { return y(d.y); });

svg.append("path")
    .datum(dataBelowLine)
    .attr("class", "areaAbove")
    .attr("d", area);

Now since I have zoom & drag functionality, I want filled area also to be updated when chart is zoomed or dragged. Basically I want area below last line to be filled even after zoom or drag as well.

Area update not working after zoom

Below is zoomed function:-

function zoomed() {
        svg.select(".areaAbove").call(area);

        svg.select(".x.axis").call(xAxis);
        svg.select(".y.axis").call(yAxis);  

        svg.selectAll('path.line').attr('d', line);  

        points.selectAll('circle').attr("transform", function(d) { 
            return "translate(" + x(d.point.x) + "," + y(d.point.y) + ")"; }
        );  
    }

JS Fiddle code

Upvotes: 2

Views: 207

Answers (1)

Mark
Mark

Reputation: 108567

You need to update the area d attribute in your zoom function handler:

function zoomed() {
  svg.select(".areaAbove").call(area);

  svg.select(".x.axis").call(xAxis);
  svg.select(".y.axis").call(yAxis);

  svg.selectAll('path.line').attr('d', line);

  svg.select('.areaAbove').attr('d', area); //<-- add this!

  points.selectAll('circle').attr("transform", function(d) {
    return "translate(" + x(d.point.x) + "," + y(d.point.y) + ")";
  });
}

Another problem you'll have is you don't apply the clip path to your area:

svg.append("path")
  .datum(dataBelowLine)
  .attr("class", "areaAbove")
  .attr("d", area)
  .attr("clip-path", "url(#clip)");

Updated fiddle.

Upvotes: 1

Related Questions