3

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')
Community
  • 1
  • 1
Prevost
  • 677
  • 5
  • 20
  • 1
    Not sure if I understand the question, but 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, which you can read more about at (http://matplotlib.org/faq/usage_faq.html#coding-styles). Mixing both styles is (in my experience) not a good idea. – karlson Dec 28 '15 at 20:09
  • That's an answer of a comment. If you post that as a reply I would mark it as an answer for you. – Prevost Dec 31 '15 at 01:58

2 Answers2

5

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.

xnx
  • 24,509
  • 11
  • 70
  • 109
1

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)

karlson
  • 5,325
  • 3
  • 30
  • 62