【问题标题】:Pyplot claims that the Figure type does not have the attribute `add_subplot()`, but ONLY if the code is not in a classPyplot 声称 Figure 类型没有属性 `add_subplot()`,但仅当代码不在类中时
【发布时间】:2021-11-19 05:29:40
【问题描述】:

下面的代码生成一个画布,上面有两个空图,这正是它应该做的。

import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec


class MakerOfTwoEmptyPlots(object):

    def __init__(self):

        self.fig = plt.figure()
        self.gs = GridSpec(1, 2, figure=self.fig)

        self.fig.add_subplot(self.gs[0, 0])
        self.fig.add_subplot(self.gs[0, 1])


plotter = MakerOfTwoEmptyPlots()
plt.show()

但是,如果我在类之外运行完全相同的代码,如下所示:

import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

fig = plt.figure()
gs = GridSpec(1, 2, figure=fig)

fig.add_sublot(gs[0, 0])
fig.add_sublot(gs[0, 1])

plt.show()

我收到错误AttributeError: 'Figure' object has no attribute 'add_sublot',尽管代码基本相同并且self.figfig 属于同一类型(我检查了调试器)。这非常令人困惑!有人知道这里发生了什么吗?

由于这似乎是可能依赖于它的那种问题,我正在使用 Python 3.9.1、MatPlotLib 3.3.3 和 IntelliJ IDEA Community Edition 2020.3。

编辑:正如多人指出的那样,这是一个简单的错字。哎呀。感谢您看到我看不到的东西。

【问题讨论】:

  • Figure 对象确实没有 add_sublot 属性。相反,它们具有add_subplot,正如您在第一个代码块中使用的那样。看出区别了吗?
  • 这是一个错字。 fig.sublot(gs[0,0]) p 不见了。

标签: python matplotlib subplot figure


【解决方案1】:

应该是fig.subplot 而不是fig.sublot

import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

fig = plt.figure()
gs = GridSpec(1, 2, figure=fig)

fig.add_subplot(gs[0, 0])
fig.add_subplot(gs[0, 1])

plt.show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-08
    • 2020-06-14
    • 1970-01-01
    相关资源
    最近更新 更多