python - 逐步将新数据附加并绘制到 matplotlib 行

标签 python matplotlib animation plot redraw

问题

将数据附加到现有 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()

Redraw time depending on the data size

最佳答案

这是您的代码的修改版本,它使用了 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 取消注释的情况下,重绘时间为:

Redraw times

另一方面,使用 ax.set_xlim 注释:

Redrawtimes

显然,调用 fig.canvas.draw() 会重绘所有内容。在您的情况下,通过注释 ax.set_xlim([0,N_chunk]),您正在重绘轴边界、刻度标签等内容。您想要探索此 SO 中讨论的 blitting。以避免重绘轴对象。

关于python - 逐步将新数据附加并绘制到 matplotlib 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61683304/

相关文章:

python - 如何生成 SSH 代理签名响应

python - Matplotlib:在线边缘上绘制标记

python - matplotlib 轮廓可以匹配像素边缘吗?

python - 创建一个 Pandas 散点图,其中一个轴是索引

python - 我的 Python 中的二分搜索功能不起作用

python - 错误 "mismatched input"期待 DEDENT

python - 在 Python 中使用沙滩球 map (焦点机制)

jquery - 模仿 reeder 风格的截图弹出缓动

iphone - 使用图像序列的 iPhone 游戏动画的内存问题

javascript - 为什么 Canvas 在圆(弧)之间画线?