[英]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))
. 在Matplotlib中 ,许多示例以ax = subplot(111)
的形式出现,然后函数应用于ax
,如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. 或者,当我不需要子图时,我可以执行plt.figure()
,然后使用plt.plot()
或类似函数绘制我需要的任何内容。
Now, I'm exactly in the second case, but I want to call the function set_major_formatter
on the X axis. 现在,我正好在第二种情况下,但我想在X轴上调用函数set_major_formatter
。 Calling it on plt
of course won't work: 在plt
上调用它当然不会起作用:
>>> 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? 我该怎么办?
If the figure that you want is selected, just use gca()
to get the current axis instance: 如果选择了您想要的数字,只需使用gca()
获取当前轴实例:
ax = gca()
ax.xaxis.set_major_formatter(FuncFormatter(myfunc))
Another option is to use the figure object returned by figure()
. 另一种选择是使用figure()
返回的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. 处理多个图时,此选项非常有用,因为您可以指定要更新的图。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.