Python plotly dynamic plot

Viewed 2109

I've been trying to perform a visualization with Plotly, but my problem is that I need it to be dynamic. Meaning if I have the code:

import plotly.express as px 

data = [1, 5, 4, 7, 5, 2, 3, 9]
data_2 = [1, 2, 3, 4, 5, 6, 1, 5] 

area_chart = px.area(data, title='Title')
area_chart.show()

then how do I append 'data_2' to 'data' so that the numbers from 'data_2' appear dynamically on the chart after it's created every 0.5s?

1 Answers

How to do it will depend on the environment in which you are creating the plot. In Jupyter notebook you can do it as follows:

import time
import plotly.graph_objects as go
import numpy as np

# initialize and display plot
fig = go.FigureWidget()
fig.add_scatter(y=np.random.randint(0,10, 5), fill='tozeroy')
display(fig)

# modify plot using new data
for i in range(10):
    time.sleep(0.5)
    fig.data[0].y = np.random.randint(0,10, 5)

This gives:

animated plotly

Outside Jupyter notebook, you can use Dash.

Related