S.H.
S.H.

Reputation: 83

Prevent line path from overflowing graph in svg using D3

I am following this example: https://bl.ocks.org/mbostock/34f08d5e11952a80609169b7917d4172

But when I replace area in focus with line, it doesn't work properly anymore. Zooming, panning, and using brush make the line path overflow the left and right boundaries of the graph, like this:

1]

This is the screenshot of the main chart, i.e. focus, only. It doesn't include the context chart

This problem doesn't happen with the area element like in the example code. I guess I don't make appropriate updates in brushed() and zoomed(). What should I do to prevent the overflow?

Here are the changes I made to use line:

Original code:

var area = d3.area()
  .curve(d3.curveMonotoneX)
  .x(function(d) { return x(d.date); })
  .y0(height)
  .y1(function(d) { return y(d.price); });

[...]

focus.append("path")
  .datum(data)
  .attr("class", "area")
  .attr("d", area);

[...]

function brushed() {
  [...]
  focus.select(".area").attr("d", area);
  [...]
}

function zoomed() {
  [...]
  focus.select(".area").attr("d", area);
  [...]
}

My code:

var line = d3.line()
    .x(function(d) { return x(d.date); })
    .y(function(d) { return y(d.price); });

[...]

focus.append("path")
      .datum(data)
      .attr("fill", "none")
      .attr("stroke", "steelblue")
      .attr("stroke-linejoin", "round")
      .attr("stroke-linecap", "round")
      .attr("stroke-width", 1.5)
      .attr("class", "line")
      .attr("d", line);

[...]

function brushed() {
  [...]
  focus.select(".line").attr("d", line);
  [...]
}

function zoomed() {
  [...]
  focus.select(".line").attr("d", line);
  [...]
}

Thanks.

Upvotes: 2

Views: 1097

Answers (1)

nikii
nikii

Reputation: 41

Looks like you're missing clip path, that is hiding data outside chart domain. It's all in the example you're using.

CSS:

.area {
    fill: steelblue;
    clip-path: url(#clip);
}

JS:

svg.append("defs").append("clipPath")
    .attr("id", "clip")
    .append("rect")
    .attr("width", width)
    .attr("height", height);

Upvotes: 3

Related Questions