【问题标题】:Python using Matplotlib for real-time plottingPython 使用 Matplotlib 进行实时绘图
【发布时间】:2020-01-10 20:32:39
【问题描述】:

我会先说我还在学习 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 秒左右显示一次绘图值,并用绘图(线)对图表进行动画处理。

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

【问题讨论】:

  • 每个新文件是否包含单个 RSSI 值?

标签: python matplotlib jquery-animate


【解决方案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()

【讨论】:

  • 编辑:图表现在随时间更新,但没有出现图表。
  • @wiwinut 更新应该由FuncAnimation 处理,我预计如果数据未更新,问题在于读取数据。我会检查rssi_val 是否为非空
  • 更新:在监控之后,我看到 X 和 Y 值现在都出现在 X 和 Y 框的外部。但是,内部没有出现趋势线。不确定这是否清楚,我没有可能在 cmets 中发布图像。我试图说明在时间 X,RSSI 值为 Y。谢谢您迄今为止的帮助!
  • @wiwinut 您可以编辑问题以添加输出图像,我会尽力帮助您找出问题所在。如果您可以包含一些数据,这也会很有用
  • @wiwinut 看看我编辑中的方法,如果我正确理解你正在尝试做的事情,那应该是一个更好的方法。除非您每次迭代都读取多个 RSSI 值
猜你喜欢
  • 2018-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多