Fabio Gentile
Fabio Gentile

Reputation: 43

Real time DataFrame plot

I have a pandas DataFrame which is updated in a while loop and I would like to plot this in real time, but unfortunately I did not get how to do that. A samplae code might be:

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)

But if I uncomment """plt.ion()""" I get many different windows open. Otherwise I have to close the window to get the updated plot. Any suggestions?

Upvotes: 4

Views: 2482

Answers (1)

Molly
Molly

Reputation: 13610

You can specify the axes for plot to use instead of creating a different axes each time you call it. To redraw the plot in interactive mode you can use draw instead of 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)

Upvotes: 1

Related Questions