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?

Best answer

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

ax = gca()
ax.xaxis.set_major_formatter(FuncFormatter(myfunc))