Hello,
I am trying to use relayout data in order to apply the same x axis selection to all graphs on a page when the user zoom on one graph (user zoom on one graph, zoom automatically applies to all graphs).
I’ve seen several posts on the topic but none give a full example.
I have tried this:
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, ALL
# Sample data
data1 = {'x': [1, 2, 3, 4, 5], 'y1': [4, 6, 5, 8, 2]}
data2 = {'x': [2, 3, 4, 5, 6], 'y2': [2, 1, 3, 1, 5]}
# Function to generate a graph with unique ID
def generate_graph(data, graph_id):
return dcc.Graph(
id=graph_id,
figure={
'data': [{'x': data['x'], 'y': data[list(data.keys())[0]], 'name': list(data.keys())[0]}],
'layout': {'xaxis': {'title': 'X-axis'}, 'yaxis': {'title': 'Y-axis'}}
}
)
# Create Dash app
app = dash.Dash(__name__)
# Create graphs
graph1 = generate_graph(data1.copy(), 'graph1')
graph2 = generate_graph(data2.copy(), 'graph2')
# App layout
app.layout = html.Div([graph1, graph2])
# Shared callback to update both graphs on zoom
@app.callback(
Output({'type': 'graph'}, 'figure'), # Update figure of both graphs
[Input({'type': 'graph', 'index': ALL}, 'relayout')] # Listen to relayout on any graph (ALL wildcard)
)
def update_all_figures(relayout):
# Extract xaxis zoom range from relayout data (if available)
x_range = relayout.get('xaxis.range', None)
# Update figure layout with the shared zoom range (if any)
return [{'data': data['data'], 'layout': {'xaxis': {'range': x_range}}} for data in [data1, data2]]
if __name__ == '__main__':
app.run_server(debug=True)
But nothing happens when I zoom in.
Could you please let me know what I’m missing?
Thank you.