Prevost
Prevost

Reputation: 697

fig and ax properties in matplotlib plots

Which object contains the property ylim()? In the code below (I have imported the required packages and x1 and y1 plot properly) to set the y-axis limits, I have to use plt.ylim(), why is this so? In my own head, I would use ax1.ylim() because the y-axis belongs to an ax object instance. Can someone please explain why this is not correct?

I saw this post here:

Why do many examples use "fig, ax = plt.subplots()" in Matplotlib/pyplot/python

which helped clarify it a little, but I'm still unsure. Thanks!

x1 = df_mstr1['datetime'].values
y1 = df_mstr1['tons'].values
fig1, ax1 = plt.subplots()
ax1.stackplot(x1, y1, color='blue')
plt.ylim(0,300)
fig1.savefig('page.pdf', format = 'pdf')

Upvotes: 3

Views: 1380

Answers (2)

karlson
karlson

Reputation: 5433

You can use ax.set_ylim((lower, upper)) to set the limits (http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.set_ylim).

matplotlib encourages two different styles of usage. An OO-style that offers maximum flexibility and a matlab-style making heavy use of global state. The latter is useful for quick interactive exploration, the former is the way to go for production-ready fine tuned plots.

You can read more about that here.

I recommend sticking to one style, as mixing both leads to trouble (at least that's what I experienced)

Upvotes: 1

xnx
xnx

Reputation: 25550

The way I think about it is that pyplot.ylim() is the convenience function (it's not technically a property) providing a MATLAB-like functionality to set the y-limits of the current axes (the one most recently created or plotted on), whereas ax1.set_ylim() sets the y-limits of a specific axes object (there could be more than one) which you have named ax1.

plt.ylim() is good for quick plots that don't require much customization. The more object-oriented ax1.set_ylim() is better when you need to keep track of more objects related to your plot in order to customize them (and keep track of what you've customized) more clearly.

Upvotes: 5

Related Questions