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.
Author by
Ricky Robinson
Updated on July 19, 2022Comments
-
Ricky Robinson almost 2 years
In Matplotlib a lot of examples come in the form
ax = subplot(111)
and then functions are applied onax
, likeax.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 withplt.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 onplt
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 almost 7 yearsIf you get an error
NameError: name 'gca' is not defined
try usingax = plt.gca()
instead ofax = gca()