How to Plot Live Graph from Threading Queue to Multiprocessing with Responsive Window?

Viewed 8

I have some program which updates global Dataframe every few second. I want to plot live graph with that dataframe.

Dataframe updated on threading. On internet I found, to plot graph with updated dataframe we need multiprocessing.Process with Queue.

How to keep plot open with responsive window and update if dataframe changed?

My demo Code:

import threading
import time
from multiprocessing import Process,Queue
import pandas as pd
from matplotlib import pyplot as plt
print("Starting")
global df


def live_df():
    global df
    df = pd.DataFrame({"demo": range(10)})
    for n in range(10, 20):
        df = df.append([{"demo": n}], ignore_index=True)
        q.put(df)
        time.sleep(5)
        print("DataFrame Updated:", n)


def live_graph(qq):
    plt.ion()
    fig = plt.figure()
    ax = fig.add_subplot(111)

    for a in range(30):
        data = qq.get()
        print("inside Graph", a)
        ax.plot(data)
        plt.title(a)
        fig.canvas.draw()
        fig.canvas.flush_events()


if __name__ == '__main__':
    q = Queue()
    threading.Thread(target=live_df, daemon=True).start()
    p = Process(target=live_graph, args=(q,))
    p.start()
    p.join()

Is this efficient approch or I need some changes? I tried FuncAnimation but with no success.

Graph plot is not responding on time.sleep inside demo_df function, Why?

My OS is Windows.

0 Answers
Related