实时数据帧p

2024-05-26 07:47:34 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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)

但如果我取消注释“”血小板()“我打开了许多不同的窗口。否则我必须关闭窗口以获取更新的绘图。 有什么建议吗?在


Tags: columnsfromimportpandasdfdatetimetimematplotlib
1条回答
网友
1楼 · 发布于 2024-05-26 07:47:34

您可以为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)

相关问题 更多 >