1

I've a python script that receives data from a websocket, and then they are elaborated. What I'd like to do is to create a plot with matplotlib, that shows two functions on the same subplot (I need to check their intersection).

I've seen in other posts like this one that I can use FuncAnimation or create a loop and put a sleep in it, but it's not what I need; since I receive data from a websocket I don't know when those data arrives, so I cannot use a loop. The only thing that I know about timing at the moment is that those data are slow, I can receive at most one new sample every minute, so there should be no need for searching another library like pyqt with greater real-time performance.

Those are some code snippet taken around here:

import numpy as np
import matplotlib.pyplot as plt; plt.ion()
import pandas as pd

n = 100
x = np.arange(n)
y = np.random.rand(n)
# I don't get the obsession with pandas...
df = pd.DataFrame(dict(time=x, value=y))

# initialise plot and line
line, = plt.plot(df['time'], df['value'])

# simulate line drawing
for ii in range(len(df)):
    line.set_data(df['time'][:ii], df['value'][:ii]) # couldn't be bothered to look up the proper way to index in pd
    plt.draw()
    plt.pause(0.001)
import random 
from itertools import count
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

plt.style.use('fivethirtyeight')

x_vals = []
y_vals = []

index = count()


def analyse(i):

    data = pd.read_csv(<your file which is updated or live data>)#u can use the pandas or any other data frame work
    x = data['index']
    y1 = data['readings']

    plt.cla()

    plt.plot(x, y1, label='Temperature') #in my case data is temperature
    
    plt.legend(loc='upper left')
    plt.tight_layout()

ani = FuncAnimation(plt.gcf(), analyse, interval=1000) #adjust intervals for call

plt.tight_layout()
plt.show()

As you can see they uses a loop or a timer. What I need instead is to update the plot when a new websocket message arrives, and it cannot be handled this way.

What should I do in order to update a plot when new data arrives?

Jepessen
  • 11,744
  • 14
  • 82
  • 149
  • Something like proposed here https://stackoverflow.com/questions/10944621/dynamically-updating-plot-in-matplotlib? – Simon Hawe Jan 29 '22 at 21:41
  • When new data arrives, you just update the data of the lines of the plot with `set_data` . – azelcer Jan 31 '22 at 21:29

0 Answers0