plt.figure() vs subplots in Matplotlib

11,324

Solution 1

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)) 

Solution 2

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(), 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 handling several plots, as you can specify which plot will be updated.

Share:
11,324
Ricky Robinson
Author by

Ricky Robinson

Updated on July 19, 2022

Comments

  • Ricky Robinson
    Ricky Robinson almost 2 years

    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?

  • 3kstc
    3kstc almost 7 years
    If you get an error NameError: name 'gca' is not defined try using ax = plt.gca() instead of ax = gca()