Fabian
Fabian

Reputation: 83

How do i update live plots with Matplotlib

I would like my plot to be updated live. It gets a list from a function, the funktion is embedded in, the list constantly gets longer over time. Thus the plotting has to stop at a point and cant bean infnite loop. Furhermore the entire class is run in a loop.

This is the Code i came up with after days of research and programming, but unfortunatly i cant get the plpot to show up.

class LiveGraph():

    def __init__(self):

        fig = plt.figure()
        self.ax1 = fig.add_subplot(1,1,1)
        self.xar=[]
        self.yar=[]
        self.h1=self.ax1.plot(self.xar, self.yar)[0]

    def update_plot(self):
        graph_data=open("twitter-out.txt", "r")
        graph_data=list(graph_data)
        graph_data=graph_data[0].split(",")

        x=0
        y=0

        for l in graph_data:
            x+=1
            try:
                y=float(l)
            except BaseException as e:
                pass
            self.xar.append(x)
            self.yar.append(y)

        self.h1.set_xdata(self.xar)
        self.h1.set_ydata(self.yar)
        plt.draw()

I would like to have the plot show itself while the rest of the code continues in the background.

The Code is called from within a loop getting tweets:

class StdOutListener(StreamListener):  
    def on_data(self,data):
        try:
            all_data = json.loads(data)
            text=all_data["text"]

            temp_text=TextBlob(text)
            analysis=temp_text.sentiment.polarity

            output = open("twitter-out.txt","a")
            output.write(str(analysis))
            output.write(",")
            output.close()

            print("sucsess")

            live_graph=LiveGraph()
            live_graph.update_plot()

            return True

        except BaseException as e:
            print('Failed: ', str(e))

This loop is part of the tweepy libary and gets triggered each time a tweet is recieved.

Upvotes: 0

Views: 118

Answers (1)

knh190
knh190

Reputation: 2882

There's an interactive mode for matplotlib so you can detach drawing process from other code:

import matplotlib.pyplot as plt
plt.ion()
plt.plot([1,2,3]) # plots show here

# other stuff

Or you can call plt.show(block=False). From doc:

In non-interactive mode, display all figures and block until the figures have been closed; in interactive mode it has no effect unless figures were created prior to a change from non-interactive to interactive mode (not recommended). In that case it displays the figures but does not block.

A single experimental keyword argument, block, may be set to True or False to override the blocking behavior described above.

In your case you may change your last line to show(block=False).

Upvotes: 1

Related Questions