-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathdash-streaming.py
More file actions
executable file
·90 lines (69 loc) · 2.32 KB
/
dash-streaming.py
File metadata and controls
executable file
·90 lines (69 loc) · 2.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#!/usr/bin/env python3
# /// script
# requires-python = ">=3.13"
# dependencies = [
# "dash",
# "plotly",
# ]
# ///
# See https://docs.astral.sh/uv/guides/scripts/#using-a-shebang-to-create-an-executable-file
"""dash-streaming.py here.
At https://github.com/wilsonmar/python-samples/blob/main/dash-streaming.py
Use Plotly Dash library to animate a stream of real-time updates (random values) within a Flask app.
Based on https://www.perplexity.ai/search/python-code-to-create-a-dashbo-kndpQ8EfThWOL8r7a7bgsg
https://pythonprogramming.net/live-graphs-data-visualization-application-dash-python-tutorial/#google_vignette
TODO: Instead of random numbers, use real-time.
USAGE:
chmod +x dash-streaming.py
uv run dash-streaming.py
In browser: http://127.0.0.1:8050/
"""
__last_change__ = "25-10-07 v001 + new :dash-streaming.py"
__status__ = "working with random data"
import random
from collections import deque
import dash
from dash import dcc, html
from dash.dependencies import Input, Output
import plotly.graph_objs as go
app = dash.Dash(__name__)
# Set up data storage with a max length for streaming effect:
max_length = 50
times = deque(maxlen=max_length)
values = deque(maxlen=max_length)
# Initiate data:
times.append(0)
values.append(random.randint(0, 10))
app.layout = html.Div([
dcc.Graph(id='live-graph', animate=True),
dcc.Interval(
id='graph-update',
interval=1000, # Update every 1000 milliseconds (1 second)
n_intervals=0
),
])
@app.callback(Output('live-graph', 'figure'), [Input('graph-update', 'n_intervals')])
def update_graph_live(n):
"""Update live graph with new data points."""
times.append(times[-1] + 1)
values.append(values[-1] + random.uniform(-1, 1))
data = go.Scatter(
x=list(times),
y=list(values),
mode='lines+markers'
)
layout = go.Layout(
xaxis=dict(range=[max(0, times[-1] - max_length), times[-1] + 1]),
yaxis=dict(range=[min(values) - 1, max(values) + 1]),
title='Real-Time Streaming Chart'
)
return {'data': [data], 'layout': layout}
if __name__ == '__main__':
app.run(debug=True)
# app.run_server(debug=True) # previous call format obsoleted?
"""
uv run dash-streaming.py
Dash is running on http://127.0.0.1:8050/
* Serving Flask app 'dash-streaming'
* Debug mode: on
"""