2

I'd like to plot some points using matplotlib (pyplot.plot, scatter, or errorbar), apply the limits using xlim and then call a function that will adjust the Y axis limits to match the points that are visible in automated way.

MWE:

import numpy as np
from matplotlib import pyplot as plt

x = np.arange(-10, 10)
plt.plot(x, x, 'ro')
plt.xlim(-5, 5)

plt.show()

And of course the Y axis limits are approximately (-11, 10), but I'd like them to be approx. (-5, 5). I've tried following matplotlib functions: relim, set_ylim(auto=True), autoscale, autoscale_view and none of them worked. I know I could remember all the points that were plotted, limit them to given range of X values, find min and max, and set limits based on that, but I'm looking for simpler way to do that.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
rpoleski
  • 988
  • 5
  • 12
  • Thanks @MadPhysicist. [This answer](https://stackoverflow.com/a/35094823/13366024) by DanHickstein is working. I'm surprised there isn't simpler solution. The first two answers below are not what I wanted to do. They require accessing the plotted data, which I'm trying to avoid. In the code I'm working on, these data are produced in different files and passing these parameters is complicated. – rpoleski Apr 21 '20 at 06:57

2 Answers2

0

Is below is your expected result ?

enter image description here

import numpy as np
from matplotlib import pyplot as plt

x = np.arange(-10, 10)
plt.plot(x, x, 'ro')
range_min = - 5
range_max = 5

plt.xlim(range_min, range_max)
plt.ylim(range_min, range_max)

plt.show()
lostin
  • 720
  • 4
  • 10
0

You can mask your data like this:

x = np.arange(-10, 10)
y = np.sin(3 * x) + 0.5 * x

xmin = -5
xmax = +5

# compute ylim based on xlim and data
selected = y[(x >= xmin) & (x <= xmax)]
ymin = selected.min()
ymax = selected.max()

plt.plot(x, y, 'ro')
plt.xlim(xmin xmax)
plt.ylim(ymin, ymax)

plt.show()

Either matplotlib does this exact thing for you, or you do it yourself. The latter is versatile.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264