实时DataFrame图

时间:2015-05-29 17:05:37

标签: python pandas matplotlib

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

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()”“”我会打开许多​​不同的窗口。否则我必须关闭窗口才能获得更新的图。 有什么建议吗?

1 个答案:

答案 0 :(得分: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)