python - 如何使用 matplotlib 绘制日志文件的实时更新图表?

标签 python animation numpy logging matplotlib

这是迄今为止我的代码:

with open(logfile,'rb') as f:

    while True:
        lines = sum(1 for line in f)
        print lines
        X = np.arange(lines)
        data = []
        for line in f:
            a = line.split(',')
            data.append(a[1][:-2])
        print data
        Y = np.array(data)
        plt.ion()
        graph = plt.plot(X,Y)[0]
        graph.set_y_data(Y)
        plt.plot(data)
        plt.draw()
        plt.pause(0.01)

现在,当我打印数据或 Y 时,它会打印一个空数组。然后它当然会提示 XY 的尺寸不同。我想知道这是否是因为在调用打印命令之前数据填充得不够快?但是 python 应该按顺序执行,对吗?

无论如何,我认为这里的逻辑本身可能有问题。这是我最好的猜测 - 打开文件,当 True 时,尝试读取所有内容并将其发送到绘图中以供 plot.draw 使用。然后,随着文件像日志文件一样增长,图表数据和图表本身将会更新。我怎样才能确保它有效?

最佳答案

使用matplotlibs动画功能

您需要创建一个animation像这样example .

版本更新数据

首先创建一个空图并一路更新:

import time

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation


def read(logfile):
    with open(logfile) as f:
        data = []
        while True:
            line = f.readline()
            time.sleep(0.1)
            if line:
                data.append(float(line.split(',')[1][:-2]))
                yield data

def animate(values):
    x = list(range(len(values)))
    line.set_data(x, values)
    ax.set_xlim(x[0], x[-1])
    ax.set_ylim(min(values), max(values))
    return line,

fig, ax = plt.subplots()
line, = ax.plot([])


ani = FuncAnimation(fig, animate, frames=read('log.txt'), interval=10)
plt.show()

每次创建一个新绘图的版本

代码较少,但仅适用于几个步骤:

import time

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation


def read(logfile):
    with open(logfile) as f:
        data = []
        while True:
            line = f.readline()
            time.sleep(0.1)
            if line:
                data.append(float(line.split(',')[1][:-2]))
                yield data

def animate(values):
    line, = plt.plot(values, color='blue')
    return line,

fig = plt.figure(figsize = (5,5))

ani = FuncAnimation(fig, animate, frames=read('log.txt'), interval=10)
plt.show()

关于python - 如何使用 matplotlib 绘制日志文件的实时更新图表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35565551/

相关文章:

python - 如何在Python中检查查询是否插入了数据

python - gtk TreeView : place image buttons on rows

iOS Strech 动画 - 我应该从哪里开始寻找?

python - Python numpy数组索引可以为-1吗?

python - 直接从 __array_interface__ 创建 NumPy 数组

python - 如何在运行时更改工具栏中 Action 的图标?

Python 从上面的目录导入

Android:过渡到下一个 .java 的问题?

iphone - 从动画 block 中排除

python - 在 Python 中计算 Jaccard 相似度