When we plot a curve, matplotlib automatically adds some offset to the minimum and maximum points. How does matplotlib calculate this 'offset'?
E.g.
plt.plot(range(0,10))
plt.ylim()
gives the y limits (-0.45, 9.45).
while
plt.plot(np.array(range(1,10))/100)
plt.ylim()
gives the y limits (0.006, 0.094).
Not surprisingly, when I set axis
plt.plot(range(0,10))
plt.ylim(0,9)
plt.ylim()
I get (0.0, 9.0).
Often I want to set limits, but still want some margin on the limit, e.g. when the limit is on a line, the line should be nicely displayed.
Of course I can add some fraction when setting the y limit but this always requires some tweaking. I am wondering if there is a smarter way to do it.
Following @DavidG 's comment, we add the correct amount by using the margins plt.margins() or ax.margins().
Taking the given example in the question:
d = range(0, 10)
plt.plot(d)
ymarg = (max(d) - min(d)) * plt.margins()[1]
plt.ylim(min(d) - ymarg, max(d) + ymarg)
plt.ylim()
which returns (-0.45, 9.45).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With