【问题标题】:plt.figure() vs subplots in Matplotlibplt.figure() 与 Matplotlib 中的子图
【发布时间】:2013-01-04 16:13:42
【问题描述】:

Matplotlib 中,很多示例以 ax = subplot(111) 的形式出现,然后函数应用于 ax,例如 ax.xaxis.set_major_formatter(FuncFormatter(myfunc))。 (找到here

或者,当我不需要子图时,我可以只做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'

我应该在这里做什么?

【问题讨论】:

  • 我希望我能多次投票...我还没有“打破表面”并真正理解子情节和数字背后的推理以及为什么子情节似乎具有更大的“力量”即能力配置等

标签: python graph matplotlib plot


【解决方案1】:

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

当您处理多个绘图时,此选项非常有用,因为您可以指定要更新的绘图。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 如果您收到错误NameError: name 'gca' is not defined,请尝试使用ax = plt.gca() 而不是ax = gca()
    猜你喜欢
    • 2017-12-12
    • 1970-01-01
    • 2016-02-01
    • 2021-10-12
    • 1970-01-01
    • 2020-12-15
    • 2016-04-16
    • 2023-03-24
    • 1970-01-01
    相关资源
    最近更新 更多