Python使用Matplotlib进行实时绘图

问题描述 投票:1回答:1

enter image description here我将以说我仍在学习Python来作为开头,因此请保持耐心和耐心。我的代码如下:

  • 网络上的客户端每隔约5秒钟向SCP服务器发送一个文本文件(stats.txt)。 Python代码位于服务器上。

下面的代码开始:

import matplotlib.pyplot as plt
import csv
import datetime


x = []
y = []
rssi_val = []



def animate(i):
    with open('stats.txt', 'r') as searchfile:
        time = (searchfile.read(5))
        for line in searchfile:
            if 'agrCtlRSSI:' in line:
                rssi_val = line[16:20]

    y = [rssi_val]

    x = [time for i in range(len(y))]

    plt.xlabel('Time')
    plt.ylabel('RSSI')
    plt.title('Real time signal strength seen by client X')
    #plt.legend()


    plt.plot(x,y)

    ani = FuncAnimation(plt.gcf(), animate, interval=5000)

    plt.tight_layout()

    #plt.gcf().autofmt_xdate()

    plt.show()
  • SCP服务器每5秒钟打开一次文件,并绘制从文件中解析出的值。时间在X轴上绘制,而RSSI值在Y轴上绘制。

我知道目前使用的代码和方法效率不高,将来会进行修改。现在,我只希望每5秒钟左右显示一次绘图值,并使用该绘图(线)对图表进行动画处理。

运行它不会产生任何结果。

python matplotlib jquery-animate
1个回答
1
投票

您需要接电话

ani = FuncAnimation(plt.gcf(), animate, interval=5000)

在功能animate之外,然后假设已正确接收和读取数据,您应该会看到绘图更新。您可能还需要根据执行脚本的方式将plt.show()放在FuncAnimation()行之后。


编辑

您可能想尝试类似的方法

import matplotlib.pyplot as plt
import csv
import datetime

x = []
y = []
rssi_val = []

def animate(i):
    with open('stats.txt', 'r') as searchfile:
        time = (searchfile.read(5))
        for line in searchfile:
            if 'agrCtlRSSI:' in line:
                rssi_val = line[16:20]

    y.append(rssi_val)
    x.append(time)

    plt.cla()
    plt.plot(x,y)
    plt.xlabel('Time')
    plt.ylabel('RSSI')
    plt.title('Real time signal strength seen by client X')
    plt.tight_layout()

ani = FuncAnimation(plt.gcf(), animate, interval=5000)
plt.show()
© www.soinside.com 2019 - 2024. All rights reserved.