Skip to content

Instantly share code, notes, and snippets.

@AnnMarieW
Last active June 15, 2022 18:06
Show Gist options
  • Save AnnMarieW/fc574656b79204026ce3ade22d920383 to your computer and use it in GitHub Desktop.
Save AnnMarieW/fc574656b79204026ce3ade22d920383 to your computer and use it in GitHub Desktop.
Using clientside callback to update a figure with real time data
# See more info: https://stackoverflow.com/questions/63589249/plotly-dash-display-real-time-data-in-smooth-animation/63681810#63681810
from dash import Dash, dcc, html
import numpy as np
from dash.dependencies import Input, Output, State
# Example data (a circle).
resolution = 1000
t = np.linspace(0, np.pi * 2, resolution)
x, y = np.cos(t), np.sin(t)
figure = dict(
data=[{"x": [], "y": []}],
layout=dict(xaxis=dict(range=[-1, 1]), yaxis=dict(range=[-1, 1])),
)
app = Dash(__name__, update_title=None) # remove "Updating..." from title
app.layout = html.Div(
[
dcc.Graph(id="graph", figure=dict(figure)),
dcc.Interval(id="interval", interval=25),
dcc.Store(id="offset", data=0),
dcc.Store(id="store", data=dict(x=x, y=y, resolution=resolution)),
]
)
app.clientside_callback(
"""
function (n_intervals, data, offset) {
offset = offset % data.x.length;
const end = Math.min((offset + 10), data.x.length);
return [[{x: [data.x.slice(offset, end)], y: [data.y.slice(offset, end)]}, [0], 500], end]
}
""",
Output("graph", "extendData"), Output("offset", "data"),
Input("interval", "n_intervals"),
State("store", "data"), State("offset", "data"),
)
if __name__ == "__main__":
app.run_server(debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment