Matplotlib点击按钮绘图被覆盖,如何实现更新而非重绘?
问题:点击按钮后图表重复绘制而非更新
每次点击"Get Cooling Profile"按钮时,代码会重新创建图表并叠加在原有绘图上,而非更新已有图表。尝试过axes.clear()但未解决问题。
原代码:
def plot_cr(): section_length = 220 section_width = 220 angle = np.linspace(np.pi, 3 * np.pi / 2, 150) side_view_width = float(section_width) / 100 outer_radius = float(12) + side_view_width x = float(12) * np.cos(angle) y = float(12) * np.sin(angle) fig1 = Figure(figsize=(10, 10), dpi=60) axes = fig1.add_subplot(111) axes.clear() axes.plot(x, y, color="green") axes.set_aspect(1) axes.set_title('Caster Diagram') canvas_side = FigureCanvasTkAgg(fig1, master=caster_graph) canvas_side.draw() canvas_side.get_tk_widget().pack(side="left", fill="both", expand=True) axes.get_xaxis().set_visible(False) axes.get_yaxis().set_visible(False) plt.rcParams['axes.formatter.useoffset'] = False fig1.tight_layout() plot_button = Button(master=cnozzle, command=plot_cr, height=1, width=20, text="Get Cooling Profile") plot_button.grid(row=2, column=0, padx=25, columnspan=2, pady=5)
修复方案
问题核心是每次点击都重复创建Figure、FigureCanvasTkAgg实例并执行pack(),导致新图表叠加在旧图表上。需要将图表的初始化逻辑与更新逻辑分离:
- 把
fig、axes、canvas这些对象的创建移到函数外部,只初始化一次 - 在
plot_cr函数中仅执行数据更新、图表清除与重绘操作
修改后的代码:
# 初始化图表对象(只执行一次) fig1 = Figure(figsize=(10, 10), dpi=60) axes = fig1.add_subplot(111) axes.set_aspect(1) axes.set_title('Caster Diagram') axes.get_xaxis().set_visible(False) axes.get_yaxis().set_visible(False) plt.rcParams['axes.formatter.useoffset'] = False fig1.tight_layout() canvas_side = FigureCanvasTkAgg(fig1, master=caster_graph) canvas_side.get_tk_widget().pack(side="left", fill="both", expand=True) def plot_cr(): section_length = 220 section_width = 220 angle = np.linspace(np.pi, 3 * np.pi / 2, 150) side_view_width = float(section_width) / 100 outer_radius = float(12) + side_view_width x = float(12) * np.cos(angle) y = float(12) * np.sin(angle) # 清除旧绘图并更新新数据 axes.clear() axes.plot(x, y, color="green") # 重置标题和坐标轴设置(因为clear会清除这些) axes.set_aspect(1) axes.set_title('Caster Diagram') axes.get_xaxis().set_visible(False) axes.get_yaxis().set_visible(False) # 重绘画布 canvas_side.draw() plot_button = Button(master=cnozzle, command=plot_cr, height=1, width=20, text="Get Cooling Profile") plot_button.grid(row=2, column=0, padx=25, columnspan=2, pady=5)
关键修改点说明
- 将图表初始化代码(创建fig、axes、canvas)移到函数外,确保只执行一次
- 函数内仅负责计算新数据、清除旧绘图、绘制新曲线,并调用
canvas_side.draw()更新显示 - 注意
axes.clear()会清除标题、坐标轴设置等,所以需要在函数内重新设置这些属性
内容的提问来源于stack exchange,提问作者Prashant Priyadarshi
相关产品推荐
相关产品推荐

