实时DataFrame绘图

4

我有一个Pandas DataFrame,它在while循环中更新,我想实时绘制它,但是不幸的是我不知道如何做到这一点。 一个示例代码可能是:

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
import time as tm
from datetime import datetime, date, time
import pandas as pd

columns = ["A1", "A2", "A3", "A4","A5", "B1", "B2", "B3", "B4", "B5", "prex"]
df = pd.DataFrame()
"""plt.ion()"""
plt.figure()
while not True:

    now = datetime.now()
    adata = 5 * np.random.randn(1,10) + 25.
    prex = 1e-10* np.random.randn(1,1) + 1e-10
    outcomes = np.append(adata, prex)
    ind = [now]
    idf = pd.DataFrame(np.array([outcomes]), index = ind, columns = columns)
    df = df.append(idf)
    ax = df.plot(secondary_y=['prex'])

    plt.show()
    time.sleep(0.5)

但是如果我取消注释“plt.ion()”,将会打开许多不同的窗口。否则,我必须关闭窗口才能获得更新的绘图。

有什么建议吗?


我不太清楚,但我只是添加了一个“matplotlib”标签以获得更多的浏览量。似乎“bokeh”更偏向于实时内容,所以你可能需要研究一下它。 - JohnE
谢谢!我会看一下。 - Fabio Gentile
1个回答

1

您可以指定plot使用的轴,而不是每次调用时创建不同的轴。要在交互模式下重新绘制图形,可以使用draw而不是show。

from matplotlib import animation
import time as tm
from datetime import datetime, date, time
import pandas as pd

columns = ["A1", "A2", "A3", "A4","A5", "B1", "B2", "B3", "B4", "B5", "prex"]
df = pd.DataFrame()
plt.ion()
fig = plt.figure()
ax = fig.add_subplot(111) # Create an axes. 
while True:

    now = datetime.now()
    adata = 5 * np.random.randn(1,10) + 25.
    prex = 1e-10* np.random.randn(1,1) + 1e-10
    outcomes = np.append(adata, prex)
    ind = [now]
    idf = pd.DataFrame(np.array([outcomes]), index = ind, columns = columns)
    df = df.append(idf)
    df.plot(secondary_y=['prex'], ax = ax) # Pass the axes to plot. 

    plt.draw() # Draw instead of show to update the plot in ion mode. 
    tm.sleep(0.5)

谢谢,看起来它能工作,但是每次刷新都会增加行数。例如,在第一次刷新时,我有11行,在第二次刷新时有22行,依此类推...为什么会这样? - Fabio Gentile
尝试在绘制之前的每次迭代中清除轴(ax.cla())。 - Molly

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接