Python实时绘图 [英] Python realtime plotting
问题描述
我以两个数组获取一些数据:一个用于时间,一个用于值.当我达到1000点时,我会触发信号并绘制这些点(x =时间,y =值).
I acquire some data in two arrays: one for the time, and one for the value. When I reach 1000 points, I trigger a signal and plot these points (x=time, y=value).
我需要保持先前绘制的图形不变,但只有一个合理的数字,以免减慢处理速度.例如,我想在图表上保留10,000点. matplotlib交互式绘图工作正常,但我不知道如何删除第一个点,这会很快减慢计算机速度. 我查看了matplotlib.animation,但它似乎只重复了相同的情节,并没有真正实现它.
I need to keep on the same figure the previous plots, but only a reasonable number to avoid slowing down the process. For example, I would like to keep 10,000 points on my graph. The matplotlib interactive plot works fine, but I don't know how to erase the first points and it slows my computer very quickly. I looked into matplotlib.animation, but it only seems to repeat the same plot, and not really actualise it.
我真的在寻找一种简便的解决方案,以避免速度变慢.
I'm really looking for a light solution, to avoid any slowing.
在获取大量时间后,我会擦除每个循环上的输入数据(第1001个点存储在第1行中,依此类推).
As I acquire for a very large amount of time, I erase the input data on every loop (the 1001st point is stored in the 1st row and so on).
这是我现在拥有的,但是它使所有要点保持在图形上:
Here is what I have for now, but it keeps all the points on the graph:
import matplotlib.pyplot as plt
def init_plot():
plt.ion()
plt.figure()
plt.title("Test d\'acqusition", fontsize=20)
plt.xlabel("Temps(s)", fontsize=20)
plt.ylabel("Tension (V)", fontsize=20)
plt.grid(True)
def continuous_plot(x, fx, x2, fx2):
plt.plot(x, fx, 'bo', markersize=1)
plt.plot(x2, fx2, 'ro', markersize=1)
plt.draw()
我调用了一次init函数,并且continous_plot处于进程中,每次我的数组中有1000点时都会调用该函数.
I call the init function once, and the continous_plot is in a process, called every time I have 1000 points in my array.
推荐答案
您可能拥有的最简单的解决方案是替换现有图的X和Y值. (或者,如果您的X数据不变,则仅使用Y值.一个简单的示例:
The lightest solution you may have is to replace the X and Y values of an existing plot. (Or the Y value only, if your X data does not change. A simple example:
import matplotlib.pyplot as plt
import numpy as np
import time
fig = plt.figure()
ax = fig.add_subplot(111)
# some X and Y data
x = np.arange(10000)
y = np.random.randn(10000)
li, = ax.plot(x, y)
# draw and show it
ax.relim()
ax.autoscale_view(True,True,True)
fig.canvas.draw()
plt.show(block=False)
# loop to update the data
while True:
try:
y[:-10] = y[10:]
y[-10:] = np.random.randn(10)
# set the new data
li.set_ydata(y)
fig.canvas.draw()
time.sleep(0.01)
except KeyboardInterrupt:
break
该解决方案也非常快.上面代码的最大速度是每秒100次重绘(受time.sleep
限制),我得到大约70-80,这意味着一次重绘大约需要4毫秒.但是YMMV取决于后端等.
This solution is quite fast, as well. The maximum speed of the above code is 100 redraws per second (limited by the time.sleep
), I get around 70-80, which means that one redraw takes around 4 ms. But YMMV depending on the backend, etc.
这篇关于Python实时绘图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!