Matplotlib 无法识别属性 set_xdata。

sud*_*ang 4 python pyqt matplotlib matplotlib-basemap

参考这篇文章:我一直在尝试运行以下代码来绘制和实时更新图形。但是,每次尝试运行该函数时,都会出现以下错误:AttributeError: 'list' object has no attribute 'set_xdata'

该函数的其余部分如下所示:

def getData(self):
    self.data = random.gauss(10,0.1)
    self.ValueTotal.append(self.data)
    #With value total being a list instantiated as ValueTotal = []
    self.updateData()

def updateData(self):

    if not hasattr(self, 'line'):
        # this should only be executed on the first call to updateData
        self.widget.canvas.ax.clear()
        self.widget.canvas.ax.hold(True)
        self.line = self.widget.canvas.ax.plot(self.ValueTotal,'r-')
        self.widget.canvas.ax.grid()
    else:
        # now we only modify the plotted line
        self.line.set_xdata(np.arange(len(self.ValueTotal)))
        self.line.set_ydata(self.ValueTotal)

    self.widget.canvas.draw()   
Run Code Online (Sandbox Code Playgroud)

虽然此代码起源于sebastianJake French我没有成功实现它。我做错了什么吗?是什么导致了这个错误,我该如何解决?

这仅用于示例,不会复制到我的代码中。我只是将它用作参考材料,并认为这将是与社区交流我的问题的最简单方法。我不相信以前的代码。

小智 5

正如乔金顿指出的那样: plot 返回您想要第一个元素的艺术家列表:

self.line = self.widget.canvas.ax.plot(self.ValueTotal,'r-')[0]
Run Code Online (Sandbox Code Playgroud)

因此,取第一个列表元素,即实际的行。

复制此行为的最小示例:

l = plt.plot(range(3))[0]
l.set_xdata(range(3, 6))

l = plt.plot(range(3))
l.set_xdata(range(3, 6))
Run Code Online (Sandbox Code Playgroud)

第一个运行良好,第二个给出 AttributeError。