Dash Dynamically Update Charts
In modern data visualization applications, dynamically updating charts is a very important feature that allows users to view data changes in real-time without refreshing the entire page.
In Dash, the core mechanism for dynamically updating charts is **Callback**, which allows you to dynamically update chart content when users interact with the page (such as clicking buttons, selecting dropdown menus, etc.).
### Basic Structure of Callback
A typical callback consists of the following parts:
1. **Input**: Defines the component and its property that triggers the callback.
2. **Output**: Defines the component and its property that needs to be updated.
3. **Callback Body**: Calculates and returns the output value based on the input value.
For detailed explanation of Dash callbacks, see: [
### Simple Dynamically Update Chart
Through callbacks, you can dynamically update the data and layout of charts.
The following is a complete Dash application example, where users can select a dataset through a dropdown menu to dynamically display the corresponding line chart:
## Example
from dash import Dash, html, dcc, Input, Output
import plotly.express as px
import pandas as pd
# Create Dash app
app = Dash( __name__ )
# Define sample datasets
datasets ={
'Dataset1': pd.DataFrame({
'x': [1,2,3,4,5],
'y': [10,15,13,17,21]
}),
'Dataset2': pd.DataFrame({
'x': [1,2,3,4,5],
'y': [5,10,8,12,15]
}),
'Dataset3': pd.DataFrame({
'x': [1,2,3,4,5],
'y': [20,18,22,19,25]
})
}
# Define layout
app.layout= html.Div([
html.H1("Dynamic Line Chart Example"),# Title
dcc.Dropdown(
id='dataset-dropdown',# Dropdown ID
options=[{'label': name,'value': name}for name in datasets.keys()],# Dropdown options
value='Dataset1'# Default selected dataset
),
dcc.Graph(id='line-chart')# Graph component for displaying line chart
])
# Define callback
@app.callback(
Output('line-chart','figure'),# Output to figure property of Graph component with id 'line-chart'
Input('dataset-dropdown','value')# Input from value property of dropdown with id 'dataset-dropdown'
)
def update_line_chart(selected_dataset):
# Get selected dataset
df = datasets
# Create line chart using Plotly Express
fig = px.line(df, x='x', y='y', title=f'{selected_dataset} Line Chart')
return fig
# Run app
if __name__ =='__main__':
app.run_server(debug=True)# Start app, debug=True means enable debug mode
The display is as follows:
!(#)
### Code Analysis
**1. Layout section**:
* Use `html.H1` to create a title "Calculate Square".
* Use `dcc.Input` to create a number input box, with `id` as 'number-input', type as 'number'.
* Use `html.Div` to create an area for displaying results, with `id` as 'output'.
**2. Callback**:
* Use `@app.callback` decorator to define the callback.
* Input is the `value` property of the 'number-input' input box.
* Output is the `children` property of the 'output' Div.
* In the callback:
* Check if the input is empty.
* Convert the input to a float and calculate the square.
* Return the formatted result.
**4. Run the app**:
* Use `app.run_server(debug=True)` to start the app, `debug=True` means enable debug mode.
YouTip