问题
将数据附加到现有 matplotlib 线并仅绘制线的添加部分而不重新绘制整条线的方法是什么?
评论
以下是一个简单的代码,绘制了重绘时间与我们将一部分数据附加到该行的次数。
您会看到重绘时间随着行中数据的总 大小几乎呈线性增长。这表明整条线都被重绘了。我正在寻找一种方法来仅绘制该线的新部分。在这种情况下,对于下面的代码,重绘时间预计几乎不变。
import matplotlib.pyplot as plt
import numpy as np
import time
# User input
N_chunk = 10000
N_iter = 100
# Prepare data
xx = list(range(N_chunk))
yy = np.random.rand(N_chunk).tolist()
# Prepare plot
fig, ax = plt.subplots()
ax.set_xlim([0,N_chunk]) # observe only the first chunk
line, = ax.plot(xx,yy,'-o')
fig.show()
# Appending data and redraw
dts = []
for i in range(N_iter):
t0 = time.time()
xs = xx[-1]+1
xx.extend(list(range(xs,xs+N_chunk)))
yy.extend(np.random.rand(N_chunk).tolist())
line.set_data(xx,yy)
fig.canvas.draw()
dt = time.time() - t0
dts.append(dt)
plt.pause(1e-10)
plt.close()
# Plot the time spent for every redraw
plt.plot(list(range(N_iter)), dts, '-o')
plt.xlabel('Number of times a portion is added')
plt.ylabel('Redraw time [sec]')
plt.grid()
plt.show()
最佳答案
这是您的代码的修改版本,它使用了 matplotlib
的交互模式。
import matplotlib.pyplot as plt
import numpy as np
import time
# User input
N_chunk = 10000
N_iter = 100
# Prepare data
xx = np.arange(N_chunk)
yy = np.random.rand(N_chunk)
# Prepare plot
fig, ax = plt.subplots()
#ax.set_xlim([0,N_chunk]) # observe only the first chunk
line = ax.plot(xx,yy,'-o')
plt.ion() # set interactive mode
fig.show()
# Appending data
dts = []
for i in range(N_iter):
t0 = time.time()
xs = xx[-1]+1
xx=np.arange(xs,xs+N_chunk)
yy=np.random.rand(N_chunk)
line=ax.plot(xx,yy,'-o')
fig.canvas.draw()
dt = time.time() - t0
dts.append(dt)
plt.pause(1e-10)
plt.close()
# Plot the time spent for every redraw
plt.plot(range(N_iter), dts, '-o')
plt.xlabel('Number of times a portion is added')
plt.ylabel('Redraw time [sec]')
plt.grid()
plt.show()
在 ax.set_xlim
取消注释的情况下,重绘时间为:
另一方面,使用 ax.set_xlim
注释:
显然,调用 fig.canvas.draw()
会重绘所有内容。在您的情况下,通过注释 ax.set_xlim([0,N_chunk])
,您正在重绘轴边界、刻度标签等内容。您想要探索此 SO 中讨论的 blitting。以避免重绘轴对象。
关于python - 逐步将新数据附加并绘制到 matplotlib 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61683304/