Plt.figure () vs subplots in Matplotlib

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

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

Now I am exactly in the second case, but I want to call the set_major_formatter function on the X axis. Calling it on plt , of course, will not 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 am I supposed to do here?

+6
source share
2 answers

If the drawing you selected is selected, simply use gca() to get an instance of the current axis:

 ax = gca() ax.xaxis.set_major_formatter(FuncFormatter(myfunc)) 
+6
source

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

 fig = plt.figure() # Create axes, either: # - Automatically with plotting code: plt.line(), plt.plot(), plt.bar(), etc # - Manually add axes: ax = fig.add_subplot(), ax = fig.add_axes() fig.axes[0].get_xaxis().set_major_formatter(FuncFormatter(myfunc)) 

This option is very useful when you are processing multiple schedules, as you can specify which schedule will be updated.

+2
source

All Articles