Python实时绘图

CoM*_*tel 5 python plot real-time

我在两个数组中获取了一些数据:一个用于时间,一个用于值.当我达到1000点时,我触发一个信号并绘制这些点(x =时间,y =值).

我需要在前面的图中保持相同的数字,但只是一个合理的数字,以避免减慢过程.例如,我想在我的图表上保留10,000点.matplotlib交互式绘图工作正常,但我不知道如何擦除第一个点,它会很快地减慢我的计算机速度.我查看了matplotlib.animation,但它似乎只是重复相同的情节,并没有真正实现它.

我真的在寻找一个轻松的解决方案,以避免任何减速.

由于我获取了很长时间,我在每个循环上擦除输入数据(第1001点存储在第1行,依此类推).

这是我现在所拥有的,但它保留了图表上的所有点:

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()
Run Code Online (Sandbox Code Playgroud)

我将init函数调用一次,并且continous_plot处于一个进程中,每当我在数组中有1000个点时调用它.

DrV*_*DrV 7

您可能拥有的最轻的解决方案是替换现有绘图的X和Y值.(或者只有Y值,如果您的X数据没有变化.一个简单的例子:

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
Run Code Online (Sandbox Code Playgroud)

这个解决方案也很快.上面代码的最大速度是每秒100次重绘(受限于time.sleep),我得到70-80左右,这意味着一次重绘大约需要4毫秒.但YMMV取决于后端等.

  • 您的解决方案似乎很好,但是使用您的代码,轴被阻止,并且绘图发生在可查看域之外.我可以添加什么来自动调节轴?编辑:找到解决方案:我需要在循环中的fig.canvas.draw之前添加这两行:ax.relim()ax.autoscale_view(True,True,True) (2认同)

f.r*_*ues 5

使用固定大小的数组并使用matplot进行绘图.

 import collections
 array = collections.deque([None] * 1000, maxlen=1000)
Run Code Online (Sandbox Code Playgroud)

当您追加到数组时,它将删除第一个元素.