实时绘图 pandas 数据框 [英] realtime plotting pandas dataframe

查看:88
本文介绍了实时绘图 pandas 数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是matplotlib的新手,它试图显示通过函数read_API()从api下载的三个变量的最近一小时数据的实时图.数据位于带有DateTimeIndex的熊猫数据框中. 例如:

I am new to matplotlib and trying to display a real time plot of the last hour's data for three variables that I'm downloading from an api via my function read_API(). The data is in a pandas dataframe with a DateTimeIndex. For example:

In: dframe.head()
Out:
                                 A          B         C
timestamp                                                            
2017-05-11 16:21:55        0.724931  0.361333   0.517720  
2017-05-11 16:22:25        0.725386  0.360833   0.518632
2017-05-11 16:22:55        0.725057  0.361333   0.521157
2017-05-11 16:23:25        0.724402  0.362133   0.520002

简化的代码是:

import pandas as pd
import matplotlib.pyplot as plt
import datetime as dt
while True:
    dframe = read_API()
    dframe['timestamp'] = dframe['timestamp'] + pd.DateOffset(hours=timezone)
    dframe = dframe.set_index('timestamp')
    end = dframe.index.max()
    start= end.to_datetime() - dt.timedelta(hours=1)
    dframe = dframe.loc[start:end]
    plt.ion()
    fig, ax = plt.subplots()
    plt.pause(0.0001)
    ax.plot_date(dframe.index.to_pydatetime(), dframe,marker='', linestyle='solid')
    plt.draw()

它会平均每隔几秒钟生成一次更新的图,但是: 1)每个图在新窗口中绘制猿猴(称为图1,图2,图3 .....).我想要一个覆盖图覆盖前一个窗口的窗口 2)当每个图出现时,它是空白的.然后出现另一个空白,然后另一个,然后第一个完成,依此类推.实际绘图滞后约3个数字..... 我对情节和子情节之间的区别感到困惑,并认为问题可能与此有关.

It is producing updated plots avery few seconds , but: 1) each plot apepars in a new window (called Figure 1, Figure 2, Figure 3.....). I want a single window with the plot overwriting the previous one 2) When each plot appears, it is blank. Then another blank one appears, then another, then the first one is completed, and so on. The actual plotting lags about 3 figures behind..... I am a bit confused about the distinction between plots and subplots, and think the problem may be related to this.

推荐答案

我认为您的代码存在的问题是,每次刷新数据时,您都会调用fig, ax = plt.subplots().这每次都会创建一个新的 Figure ,因此您会看到新的框架弹出.

I think the issue with your code is that you invoke fig, ax = plt.subplots() each time you refresh your data. This creates a new Figure each time, and thus you see new frames pop up.

相反,您想在外部创建 Figure while循环中,仅刷新 Axes 加载新数据后.

Instead, you want to create the Figure outside of your while loop, and only refresh the Axes once you loaded new data.

我已经使用了您提供的基本示例来创建一个自我更新的

I've used the basic example you've provided to create a self-updating Figure.

import pandas as pd
import matplotlib.pyplot as plt 
import datetime as dt

data = [ 
    {'timestamp': '2017-05-11 16:21:55', 'A': 0.724931, 'B': 0.361333, 'C': 0.517720},
    {'timestamp': '2017-05-11 16:22:25', 'A': 0.725386, 'B': 0.360833, 'C': 0.518632},
    {'timestamp': '2017-05-11 16:22:55', 'A': 0.725057, 'B': 0.361333, 'C': 0.521157},
    {'timestamp': '2017-05-11 16:23:25', 'A': 0.724402, 'B': 0.362133, 'C': 0.520002},
]
df = pd.DataFrame(data) 
df.set_index("timestamp")

plt.ion()
fig, ax = plt.subplots()
while True:
    dframe = df.copy()
    dframe['timestamp'] = pd.to_datetime(dframe['timestamp']) + pd.DateOffset(hours=2)
    dframe = dframe.set_index('timestamp')
    end = dframe.index.max()
    start= end.to_datetime() - dt.timedelta(hours=1)
    dframe = dframe.loc[start:end]
    plt.pause(0.0001)
    ax.plot_date(dframe.index.to_pydatetime(), dframe, marker='', linestyle='solid')


编辑1

我无法复制提出的 Warning ,但是我的猜测是,它与 pause 通话.也许尝试交换以下内容并编辑暂停时间.


Edit 1

I cannot reproduce the raised Warning, but my guess would be that it's related to the pause call. Maybe try swapping the following and editing the pause time.

   ax.plot_date(dframe.index.to_pydatetime(), dframe, marker='', linestyle='solid')
   plt.pause(0.01)


编辑2

固定颜色非常简单.定义您的调色板,然后从中选择.


Edit 2

Fixing the colours is quite simple. Define your colour palette and then pick from it.

colors = ['r', 'g', 'b']

plt.ion()
fig, ax = plt.subplots()
while True:
    dframe = df.copy()
    # Your data manipulation
    # ...
    dframe = dframe.loc[start:end]
    for i, column in enumerate(dframe.columns):
        ax.plot(dframe.index.to_pydatetime(), dframe[column], color=colors[i], marker=None, linestyle='solid')   
    plt.pause(0.1)

如果您有更多列,请向colors数组添加更多颜色.或者,根据dframe中的列数即时生成它.

If you have more columns, add more colours to the colors array. Alternatively, generate it on-the-fly depending on the number of columns in dframe.

这篇关于实时绘图 pandas 数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆