Pyplot 声称 Figure 类型没有属性“add_subplot()”,但仅当代码不在 class 中时
Pyplot claims that the Figure type does not have the attribute `add_subplot()`, but ONLY if the code is not in a class
下面的代码生成一个 canvas,上面有两个空图,这正是它应该做的。
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()
但是,如果我 运行 在 class 之外使用完全相同的代码,就像这样:
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.fig
和 fig
属于同一类型(我在调试器中检查过)。这令人深感困惑!有人知道这里发生了什么吗?
由于这似乎是一种可能依赖于它的问题,我正在使用 Python 3.9.1、MatPlotLib 3.3.3 和 IntelliJ IDEA Community Edition 2020.3。
编辑:正如多人指出的那样,这是一个简单的错字。哎呀。感谢您看到我看不到的东西。
应该是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()
下面的代码生成一个 canvas,上面有两个空图,这正是它应该做的。
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()
但是,如果我 运行 在 class 之外使用完全相同的代码,就像这样:
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.fig
和 fig
属于同一类型(我在调试器中检查过)。这令人深感困惑!有人知道这里发生了什么吗?
由于这似乎是一种可能依赖于它的问题,我正在使用 Python 3.9.1、MatPlotLib 3.3.3 和 IntelliJ IDEA Community Edition 2020.3。
编辑:正如多人指出的那样,这是一个简单的错字。哎呀。感谢您看到我看不到的东西。
应该是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()