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

问题

将数据附加到现有 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。以避免重绘轴对象。

https://stackoverflow.com/questions/61683304/

相关文章:

spring-boot - 如何将Keycloak注册到Spring Eureka Server

kubernetes - 无法从普罗米修斯适配器检索自定义指标

c# - w[警告]未找到测试结果文件 azure devops

java - Netbeans 中的 JUnit 5 测试

python - 包含 json 格式列的 Dask 数据框

google-app-engine - 如何使用 Google Cloud Tasks 扩展拉取队列

python - 你如何使用 python-rtmidi 获取 midi 事件

ios - 在 iOS 13 中获取 Root View Controller 的正确方法是什么?

html - 如何在没有 JavaScript 的情况下设置 CSS 动画速度?

css - 有没有办法使用变换比例使内容自动适合父 div?