plt.figure() vs subplots in Matplotlib


In Matplotlib a lot of examples come in the form ax = subplot(111) and then functions are applied on ax, like ax.xaxis.set_major_formatter(FuncFormatter(myfunc)). (found here)

Alternatively, when I don't need subplots, I can just do plt.figure() and then plot whatever I need with plt.plot() or similar functions.

Now, I'm exactly in the second case, but I want to call the function set_major_formatter on the X axis. Calling it on plt of course won't work:

>>> plt.xaxis.set_major_formatter(FuncFormatter(myfunc)) 
Traceback (most recent call last):
File "<stdin>", line 1, in <module> 
AttributeError: 'module' object has no attribute 'xaxis'

What should I do here?

1/21/2013 3:08:51 PM

Accepted Answer

If the figure that you want is selected, just use gca() to get the current axis instance:

ax = gca()
1/21/2013 3:46:28 PM

Another option is to use the figure object returned by figure().

fig = plt.figure()

# Create axes, either:
#  - Automatically with plotting code: plt.line(), plt.plot(),, etc
#  - Manually add axes: ax = fig.add_subplot(), ax = fig.add_axes()


This option is very useful when you are handling several plots, as you can specify which plot will be updated.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow