【问题标题】:Self-updating graphs over time with Python and matplotlib使用 Python 和 matplotlib 随时间自动更新图形
【发布时间】:2015-07-06 00:49:45
【问题描述】:

我不熟悉 Python 中的 matplotlib。我想要实现的是使用文本文件随时间绘制数据,该文本文件每隔一定时期接收新数据。

文本文件格式如下:

数据,时间

1,2015-07-05 11:20:00

到目前为止我所拥有的:

import matplotlib.pyplot as plt
import matplotlib.dates as md
import dateutil

pullData = open('sampleText.txt', 'r').read()
dataArray = pullData.split('\n')

datestrings = []
plt_data = []

for eachLine in dataArray:
    if len(eachLine)>1:
        y,x = eachLine.split(',')
        plt_data.append(int(y))
        datestrings.append(x)

dates = [dateutil.parser.parse(s) for s in datestrings]

plt.subplots_adjust(bottom=0.2)
plt.xticks( rotation=25 )

ax=plt.gca()
ax.set_xticks(dates)

xfmt = md.DateFormatter('%m-%d %H:%M')
ax.xaxis.set_major_formatter(xfmt)
plt.plot(dates,plt_data, "o-")
plt.show()

这几乎是我可以通过不同的教程/以前的问题得到的。

如您所见,此代码适用于随着时间的推移绘制数据,但我不明白如何调整它以使图表使用新数据自行更新。

【问题讨论】:

  • @tom10 你说得对,我刚刚编辑了我的问题。谢谢。
  • 现在很清楚了。谢谢。我删除了我的原始评论,因为我认为您首先以通常理解的方式使用“实时”,所以现在我的原始评论只是令人困惑。

标签: python matplotlib


【解决方案1】:

假设您的文本文件正在被写入并附加新数据。

然后,您可以使用 inotify 在文件被修改时获取警报,并将函数“挂起”到该事件以更新您的图表。

查看this page,其中有几个关于如何使用 pyinotify 捕获事件的示例。还提供了minimal example,它显示了您的程序的“结构”:

import pyinotify

# Instantiate a new WatchManager (will be used to store watches).
wm = pyinotify.WatchManager()

# Associate this WatchManager with a Notifier (will be used to report and
# process events).
notifier = pyinotify.Notifier(wm)

# Add a new watch on /tmp for ALL_EVENTS.
wm.add_watch('/tmp', pyinotify.ALL_EVENTS)

# Loop forever and handle events.
notifier.loop()

最重要的是,pyinotify.ALL_EVENTS 可以改成监听 仅针对您感兴趣的事件(例如文件修改,或 如果文件不存在则创建)

【讨论】:

    【解决方案2】:

    您可以使用function animation 进行操作,也可以使用以下代码:

    line, = ax.plot(dates,plt_data, "o-")
    plt.show(block=False)
    
    while True:
      # use some method as the one proposed by jcoppens to read your new data
      line.set_data(new_dates, new_data)
      # timeout/sleep until new data arrives
    

    【讨论】:

    • 我试过你所说的作为通知者os.stat('sampleText.txt').st_mtime。但发生的情况是图形窗口自动挂起。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-01
    • 2018-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-13
    相关资源
    最近更新 更多