有什么方法可以将数据追加到现有的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])
你正在重新绘制一些东西,如轴的边界、刻度标签等。您想探索本文档中讨论的blitting。SO 以避免重绘轴对象。