Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Plot Live Graphs using Python Dash and Plotly
Python provides powerful tools like Dash and Plotly for creating interactive and dynamic visualizations. We can create live graphs to visualize data in real-time, which is essential for monitoring systems, tracking financial trends, or displaying live analytics.
This article explores how to plot live graphs using Python Dash and Plotly. We'll learn how to set up a Dash application, define the layout, and update graphs dynamically using callbacks.
Installation
Before starting, install the required packages ?
pip install dash plotly
Basic Live Graph Setup
Here's a complete example that creates a live graph updating every second with random data ?
import dash
from dash import dcc, html
from dash.dependencies import Output, Input
import plotly.graph_objs as go
import random
# Initialize the Dash app
app = dash.Dash(__name__)
# Define the layout of the app
app.layout = html.Div([
html.H2("Live Graph", style={'text-align': 'center'}),
dcc.Graph(id="live-graph", animate=True),
dcc.Interval(
id="graph-update",
interval=1000, # Update every 1000ms (1 second)
n_intervals=0
),
])
# Callback function to update the graph
@app.callback(
Output("live-graph", "figure"),
[Input("graph-update", "n_intervals")]
)
def update_graph(n):
# Generate random data
x_data = list(range(10))
y_data = [random.randint(0, 100) for _ in range(10)]
# Create the graph trace
trace = go.Scatter(
x=x_data,
y=y_data,
mode="lines+markers",
name="Live Data",
line={"color": "rgb(0, 255, 0)", "width": 3},
marker={"color": "rgb(0, 255, 0)", "size": 8},
)
# Create the graph layout
layout = go.Layout(
title=f"Live Graph - Update #{n}",
xaxis=dict(title="Time Points", range=[0, 9]),
yaxis=dict(title="Value", range=[0, 100]),
showlegend=True,
hovermode='closest'
)
return {"data": [trace], "layout": layout}
if __name__ == "__main__":
app.run_server(debug=True, port=8051)
How It Works
The live graph system consists of several key components ?
1. Dash App Initialization
Create a Dash application instance that will serve as the web server.
2. Layout Definition
The layout contains:
html.H2 Title heading
dcc.Graph The graph component with
animate=Truefor smooth transitionsdcc.Interval Timer component that triggers updates
3. Callback Function
The @app.callback decorator creates a reactive function that:
Listens to the interval timer
Generates new data
Returns updated graph figure
Advanced Live Graph with Multiple Traces
Here's an enhanced example with multiple data series ?
import dash
from dash import dcc, html
from dash.dependencies import Output, Input
import plotly.graph_objs as go
import random
from datetime import datetime, timedelta
app = dash.Dash(__name__)
# Store data in memory
data_store = {
'time': [],
'cpu': [],
'memory': [],
'network': []
}
app.layout = html.Div([
html.H2("System Monitoring Dashboard", style={'text-align': 'center'}),
dcc.Graph(id="system-graph"),
dcc.Interval(id="interval", interval=2000, n_intervals=0),
])
@app.callback(
Output("system-graph", "figure"),
[Input("interval", "n_intervals")]
)
def update_system_graph(n):
# Generate mock system data
current_time = datetime.now()
# Add new data point
data_store['time'].append(current_time)
data_store['cpu'].append(random.randint(10, 90))
data_store['memory'].append(random.randint(30, 80))
data_store['network'].append(random.randint(5, 50))
# Keep only last 20 points
if len(data_store['time']) > 20:
for key in data_store:
data_store[key] = data_store[key][-20:]
# Create traces
traces = []
colors = {'cpu': 'red', 'memory': 'blue', 'network': 'green'}
for metric in ['cpu', 'memory', 'network']:
traces.append(go.Scatter(
x=data_store['time'],
y=data_store[metric],
mode='lines+markers',
name=f'{metric.upper()} Usage',
line={'color': colors[metric], 'width': 2}
))
layout = go.Layout(
title='Live System Monitoring',
xaxis={'title': 'Time'},
yaxis={'title': 'Usage (%)'},
showlegend=True,
hovermode='x unified'
)
return {'data': traces, 'layout': layout}
if __name__ == "__main__":
app.run_server(debug=True, port=8052)
Key Components
| Component | Purpose | Key Parameters |
|---|---|---|
dcc.Interval |
Timer for updates |
interval, n_intervals
|
dcc.Graph |
Display the plot |
id, animate, figure
|
@app.callback |
Update function |
Output, Input
|
go.Scatter |
Plot trace |
x, y, mode, name
|
Running the Application
When you run the script, you'll see output like this ?
Dash is running on http://127.0.0.1:8051/ * Serving Flask app 'live_graph' * Debug mode: on * Running on http://127.0.0.1:8051 * Restarting with stat * Debugger is active!
Open the URL in your browser to see the live updating graph.
Common Use Cases
IoT Sensor Monitoring Track temperature, humidity, or other sensor data
Financial Data Display real-time stock prices or trading volumes
System Metrics Monitor CPU, memory, or network usage
Web Analytics Show live website traffic or user engagement
Conclusion
Python Dash and Plotly provide a powerful combination for creating live graphs that update in real-time. The key is using dcc.Interval components with callback functions to refresh data automatically. This approach offers a versatile solution for interactive data visualization in monitoring, analytics, and reporting applications.
