动态Matplotlib图表中清除errorbar元素时触发AttributeError的问题求助
动态Matplotlib图表中清除errorbar元素时触发AttributeError的问题求助
我想要在Matplotlib绘图中清除并重新绘制带误差棒(errorbar)的数据,同时复用同一个背景和坐标轴——这意味着我不能直接清除整个画布。用plot方法的时候,我可以通过保存并移除绘图元素(artist)轻松实现,但使用errorbar时就遇到了问题。
举个例子,下面的脚本会生成随机数据的图表,还有一个按钮可以不清除画布的情况下清除现有数据并生成/显示新的随机数据:
import mplcursors import matplotlib.pyplot as plt from matplotlib.widgets import Button import numpy as np # 原代码遗漏该导入,补上后才能正常运行 class RandomDataPlotter: def __init__(self): self.fig, self.ax = plt.subplots() self.fig.subplots_adjust(bottom=0.2) self.current_data = None self.current_errorbars = None self.cursor = None # 添加切换数据的按钮 self.button_ax = self.fig.add_axes([0.7, 0.05, 0.1, 0.075]) self.button = Button(self.button_ax, 'Toggle Data') self.button.on_clicked(self.toggle_data) self.plot_random_data() def plot_random_data(self): # 清除已有绘图元素 if self.current_data: self.current_data.remove() if self.current_errorbars: for artist in self.current_errorbars: artist.remove() if self.cursor: self.cursor.remove() # 生成随机数据 x = np.linspace(0, 10, 100) y = np.random.rand(100) y_err = np.random.rand(100) * 0.1 # 绘制带误差棒的数据 self.current_data, _, self.current_errorbars = self.ax.errorbar(x, y, yerr=y_err, fmt='o', color='blue') # 添加悬停光标 self.cursor = mplcursors.cursor(self.ax, hover=True) self.cursor.connect("add", lambda sel: sel.annotation.set_text(f"x: {sel.target[0]:.2f}\ny: {sel.target[1]:.2f}")) # 重绘画布 self.ax.relim() self.ax.autoscale_view() self.fig.canvas.draw_idle() def toggle_data(self, event): self.plot_random_data() if __name__ == "__main__": plotter = RandomDataPlotter() plt.show()
这段代码第一次运行/点击按钮时是正常的,但之后就会触发如下错误:
AttributeError: 'NoneType' object has no attribute 'canvas' Traceback (most recent call last): File "/Users/atom/hemanpro/HeMan/.venv/lib/python3.13/site-packages/matplotlib/cbook.py", line 361, in process func(*args, **kwargs) ~~~~^^^^^^^^^^^^^^^^^ File "/Users/atom/hemanpro/HeMan/.venv/lib/python3.13/site-packages/matplotlib/widgets.py", line 244, in <lambda> return self._observers.connect('clicked', lambda event: func(event)) ~~~~^^^^^^^ File "/Users/atom/hemanpro/HeMan/test_files/test2.py", line 49, in toggle_data self.plot_random_data() ~~~~~~~~~~~~~~~~~~~~~^^ File "/Users/atom/hemanpro/HeMan/test_files/test2.py", line 40, in plot_random_data self.cursor = mplcursors.cursor(self.ax, hover=True) ~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^ File "/Users/atom/hemanpro/HeMan/.venv/lib/python3.13/site-packages/mplcursors/_mplcursors.py", line 744, in cursor return Cursor(artists, **kwargs) File "/Users/atom/hemanpro/HeMan/.venv/lib/python3.13/site-packages/mplcursors/_mplcursors.py", line 264, in __init__ for canvas in {artist.figure.canvas for artist in artists}] ^^^^^^^^^^^^^^^^^^^^ AttributeError: 'NoneType' object has no attribute 'canvas'
我目前猜测问题出在有残留的绘图元素,它们已经不再关联到任何画布/图表对象,当我尝试添加悬停光标时就会触发这个错误。但我不知道该怎么清除这些残留元素,希望能得到大家的帮助。
备注:内容来源于stack exchange,提问作者ohshitgorillas
相关产品推荐
相关产品推荐

