Matplotlib双窗口动态更新数据触发add_subplot弃用警告问题咨询
问题原因分析
MatplotlibDeprecationWarning: Adding an axes using the same arguments as a previous axes currently reuses the earlier instance.
这个警告的触发原因很明确:你在每次调用Creo_ventana函数时,都会对已经存在的WINDOW1、WINDOW2窗口重复执行add_subplot(111)操作,且没有给子图设置唯一标识。在当前Matplotlib版本中该操作会复用已有的子图实例,但未来版本会默认创建新的子图,你的原有视图、大小设置逻辑就会完全失效。
另外你的代码还存在冗余逻辑问题:不需要每次更新数据都重新获取figure、重新添加子图,仅需第一次初始化时完成窗口和子图的创建即可,后续直接更新子图内容效率更高。
修复方案
1. 快速消警方案(无需修改整体逻辑)
直接给add_subplot方法添加唯一label参数,明确告知Matplotlib需要复用对应子图,即可消除警告:
# 修改对应行即可 ax1 = window1.add_subplot(111, label="window1_ax") ax2 = window2.add_subplot(111, label="window2_ax")
2. 优化逻辑方案(推荐)
将窗口、子图的初始化逻辑从循环内移到循环外,避免重复创建操作,性能和稳定性更好,修改后的完整代码如下:
import matplotlib.pyplot as plt import numpy as np def update_plot(ax, window, data, first_run): if not first_run: # 先保存用户调整后的参数 y_min, y_max = ax.get_ylim() x_min, x_max = ax.get_xlim() size = window.get_size_inches() # 清空原有内容 ax.cla() # 恢复用户调整的参数 ax.set_xlim(x_min, x_max) ax.set_ylim(y_min, y_max) window.set_size_inches(size) ax.autoscale(False) ax.autoscale_view(True, False, False) ax.set_adjustable('box') # 绘制新数据 ax.plot(data) window.canvas.draw() window.canvas.flush_events() if __name__ == "__main__": plt.ion() # 仅初始化一次窗口和子图 window1 = plt.figure('WINDOW1') ax1 = window1.add_subplot(111) window2 = plt.figure('WINDOW2') ax2 = window2.add_subplot(111) first_run = True correr = 'y' while correr == 'y': data = np.random.rand(100)*10 update_plot(ax1, window1, data, first_run) update_plot(ax2, window2, data, first_run) first_run = False correr = input('otro? y/n :')
该方案将重复的绘图逻辑封装为通用函数,移除了每次调用都重新获取窗口、添加子图的冗余操作,从根源上避免了警告触发,也能稳定保留用户手动调整的窗口大小、视图范围参数。
内容的提问来源于stack exchange,提问作者dexter
相关产品推荐
相关产品推荐

