Search code examples
pythonmatplotliblimit

How does matplotlib calculate the min / max axis values? Or how to automatically add the matplotlib margin when setting the limits


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.


Solution

  • 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).