davidlav
davidlav

Reputation: 688

Linear piecewise scale in D3

I want to make a scale that is linear between 50 and 100, but if any outlier value is below 50 or above 100, gets coerced to a value of either 50 or 100, respectively, so that it doesn't fall off the visible range of my chart. (The plan is then to style those data points differently so that the user knows they're either more than or less than what they appear to be.)

enter image description here

How would I go about make a linear piecewise scale in D3 that does this? Or is it easier just to make a "gatekeeper" function that gets called directly by the SVG's y attribute, does those coercions manually, and then calls a regularly linear scale with "in-range" values, so that "out-of-range" values are never sent to the regular linear scale in the first place?

Upvotes: 1

Views: 548

Answers (2)

davidlav
davidlav

Reputation: 688

Actually, I just realized that linear.clamp(true) does exactly what I wanted.

Upvotes: 3

Mark
Mark

Reputation: 108537

I think you are over complicating this.

I'm sure you are using a d3.line function, just cap the values in the y accessor:

var line = d3.line()
  .x(function(d) { return x(d.x); })
  .y(function(d) { 
    if (d.y > 150) return y(150);
    else if (d.y < 50) return y(50);
    else return y(d.y);
  });

Upvotes: 3

Related Questions