How to update a shown figure in Jupyter notebook?

I would like to dynamically modify a figure after it has been shown in a jupyter notebook. Ideally this could be done in a single cell, but manipulating a figure in a following cell would work as well.

Currently if I try to call ‘add_traces’ on a figure in a cell following an initial call to .show() I get a new figure displayed. If I do this in a loop N times with a sleep between calls I get N new figures.

The messages system seems to imply that python should be able to communicate with an existing JS frontend, but I don’t seem to be able to get this to work in a notebook.

Is this possible and, if so, how would I accomplish this?

Thanks for any help or pointers!

@iandanforth

In order to stop displaying a new figure after each update, just add a semicolon at the end of an update line:

import plotly.graph_objects as go
import numpy as np


trace = dict(
            x=np.arange(8),
            y=-1.5*np.random.rand(8),
            line=dict(color='magenta'))

fig = go.Figure([trace])
fig.show()
for  k in range(N):
      fig.add_trace(...);   
fig.show()        

In this case you displayed the initial figure and the final one, resulted after all updates.

But if you want to display just one figure, define it as an instance of go.FigureWidget, and each update can be seen on the initially displayed figure:

fig  = go.FigureWidget([trace])
fig
for  k in range(N):
      fig.add_trace(...);   

That doesn’t make a lot of sense to me, can you elaborate please? The semi-colon is only needed if the add_trace() call is the last call in a notebook cell.

three reasons why you should buy plotly pro: support open source, get great support, host your plots and dashboards online