如何不用matplotlib的animation函数实现numpy数组实时绘图并解决空图问题
问题修复方案
你遇到的空白图问题主要由四个核心错误导致:
- 缺失
matplotlib.pyplot导入,代码中调用的plt未定义 - 未开启matplotlib交互模式,默认非交互模式下
plt.show()会阻塞后续代码执行,循环内的绘图逻辑完全不会运行 - 仅调用
canvas.draw()没有刷新GUI事件队列,画面不会触发实际更新 - 未提前固定坐标轴范围,可能出现线条落在可视区域外的问题
修改后可正常运行的完整代码如下:
import numpy as np import time import matplotlib.pyplot as plt from matplotlib.lines import Line2D class Plot: def __init__(self,f,axis,data): self.fig = f self.axis = axis self.data = data # 提前固定坐标轴范围,适配0-1的随机数输入 self.axis.set_xlim(0, 1) self.axis.set_ylim(0, 1) def plotting(self,i): xs = [self.data[i,0],self.data[i+1,0]] ys = [self.data[i,1],self.data[i+1,1]] line, = self.axis.plot(xs,ys,'g-') self.fig.canvas.draw() # 刷新GUI事件队列,触发画面更新 self.fig.canvas.flush_events() # 开启交互模式 plt.ion() data = np.random.rand(10,2) #numpy array f = plt.figure() axis = f.add_axes([0.1,0.1,0.8,0.8]) plotData = Plot(f,axis,data) for i in range(len(data)-1): plotData.plotting(i) time.sleep(1) # 关闭交互模式,保持最后窗口不自动关闭 plt.ioff() plt.show()
上述代码保留了你原有保留所有历史绘制轨迹的逻辑,如果需要每次仅显示单段线条,可在plotting方法开头添加self.axis.cla()清空上一帧内容,同时重设坐标轴范围即可。
内容的提问来源于stack exchange,提问作者Monojit Sarkar
相关产品推荐
相关产品推荐

