Plot real-time data

What is the proper way to produce a Real-Time Plot, i.e. dynamically update the plot as new data arrives?

What I have so far is this:

import time
import plotly.graph_objects as go

data = [1,3,2,4,3,3,2,3]

Initialize the plot:

fig = go.FigureWidget()
fig.add_scatter()
fig

Dynamic updating:

Method I

for i in range(len(data)):
    time.sleep(0.3)
    fig.data[0].y = data[:i] 

Method II

for i in range(len(data)):
    time.sleep(0.3)
    with fig.batch_update():
        fig.data[0].y = data[:i]

Both produce the following dynamic plot:

Questions:

  1. What is the difference between these 2 methods?
  2. Which is the advisable method?
  3. This works in Jupyter environments. How do I implement something like this outside of Jupyter?
1 Like

You can also take a look at Dash applications (https://dash.plot.ly). For example, this app https://dash-gallery.plotly.host/dash-wind-streaming/ queries a database for updates and then updates the figure. The source code is here https://github.com/plotly/dash-sample-apps/blob/master/apps/dash-wind-streaming/app.py

2 Likes

That is a very nice example, Emmanuelle.
I also found this one: https://dash.plot.ly/live-updates.

But, I still wold like to know the answer to the first question if you or anyone else can help :slight_smile:

1 Like

For your first question (what is the difference between using fig.batch_update and updating directly the trace data), here it does not make much of a difference because you only have one method call to update the FigureWidget. Using fig.batch_update is interesting when you have several update calls, because then they are batched together in a single patch sent only once to update the figure. See the docstring of fig.batch_update and its examples https://plot.ly/python-api-reference/generated/plotly.graph_objects.Figure.html#plotly.graph_objects.Figure.batch_update for more details.

1 Like