When we plot a curve, matplotlib automatically adds some offset to the minimum and maximum points. How does matplotlib calculate this 'offset'?
Eg
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, eg 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.
According to what I can find in the source, the margin is set as a fraction of the data range with the axes.xmargin
/ axes.ymargin
parameters, but the computation is rather more involved .
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)
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.