John
John

Reputation: 401

D3 v4 - Brush and Zoom - rescale y axis

Please see the following example:

http://nvd3.org/examples/lineWithFocus.html

When the chart is zoomed in, the y axis adjusts and scales to the data which is currently visible.

Please see the following example which works with D3 v4:

https://bl.ocks.org/mbostock/34f08d5e11952a80609169b7917d4172

Notice how the y axis does not adjust when the data is zoomed in, either by extending/shrinking the brushed area, or by zooming with the mouse wheel.

I have set this up as a fiddle here:

http://jsfiddle.net/r19LL1a4/4/

Does anyone have any insight as to how this might be accomplished?

I assume that the following section of code will need adjusting so that the yAxis is updated, but I'm not sure how to do it.

function zoomed() {
  if (d3.event.sourceEvent && d3.event.sourceEvent.type === "brush") return; // ignore zoom-by-brush
  var t = d3.event.transform;
  x.domain(t.rescaleX(x2).domain());
  focus.select(".area").attr("d", area);
  focus.select(".axis--x").call(xAxis);
  context.select(".brush").call(brush.move, x.range().map(t.invertX, t));
}

Upvotes: 0

Views: 1689

Answers (1)

John
John

Reputation: 401

I've updated the fiddle with a possible solution:

http://jsfiddle.net/r19LL1a4/40/

At least for the zoomed function:

function zoomed() {
  if (d3.event.sourceEvent && d3.event.sourceEvent.type === "brush") return; // ignore zoom-by-brush
  var t = d3.event.transform;
    x.domain(t.rescaleX(x2).domain());
  var domain= x.domain();

  y.domain([d3.min(dataperm.map(function(d) {     
          if(parseInt(d.date.getTime())> parseInt(domain[0].getTime()) && parseInt(d.date.getTime()) < parseInt(domain[1].getTime())){
          return parseFloat(d.price);  
          }})), d3.max(dataperm.map(function(d) { 

          if(parseInt(d.date.getTime())> parseInt(domain[0].getTime()) && parseInt(d.date.getTime()) < parseInt(domain[1].getTime())){
          return d.price;
    }}))]);   

  focus.select(".area").attr("d", area);
  focus.select(".axis--x").call(xAxis);
  focus.select(".axis--y").call(yAxis);

  context.select(".brush").call(brush.move, x.range().map(t.invertX, t));
}

The data needs to be saved into a global variable, dataperm. The x domain can then be applied against this to get the min and max y variables for the current domain.

Upvotes: 4

Related Questions