Python 使用 Matplotlib 进行实时绘图

Python using Matplotlib for real-time plotting

我要先说我还在学习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()

我了解到目前使用的代码和方法效率不高,以后会修改。现在,我只希望每 5 秒左右显示绘图值并使用绘图(线)对图表进行动画处理。

运行它什么都不产生。

你需要有线

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

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


编辑

您可能想试试这样的方法

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()