Matplotlib中的plt.figure()与subplots的比较

11 投票
2 回答
11568 浏览
提问于 2025-04-17 13:18

Matplotlib这个绘图库中,很多例子都是用 ax = subplot(111) 这种方式来创建一个图表,然后在这个 ax 上调用一些函数,比如 ax.xaxis.set_major_formatter(FuncFormatter(myfunc))。你可以在这里找到相关信息。

另外,如果我不需要子图的话,我可以直接用 plt.figure() 来创建一个图形,然后用 plt.plot() 或者其他类似的函数来绘制我想要的内容。

现在,我正好处于第二种情况,但我想在X轴上调用 set_major_formatter 这个函数。直接在 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'

我该怎么做呢?

2 个回答

3

另一个选择是使用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)) 

这个选择在你处理多个图表时非常有用,因为你可以指定哪个图表会被更新。

11

如果你想要的图形已经被选中了,只需要使用 gca() 来获取当前的坐标轴实例:

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

撰写回答