hi @JonasDB
You can probably do it by reading the legend interactivity, using the dcc.Graph’s restyleData
property as an Input of a callback. However, it’s a bit complicated to differentiate betwixt the legend item clicked once, clicked twice, and those not clicked. Plus, I’m not sure how common it is to create interactions between several graphs using the legend. The legend is commonly used to filter in and out data within its respective graph.
I’ve added code that creates interactivity between two graphs using hover data.
from dash import Dash, html, dash_table, dcc, callback, Output, Input
import pandas as pd
import plotly.express as px
df = px.data.gapminder().query("continent=='Africa'")
country_index_list=df.country.unique()
fig = px.line(df, x="year", y="lifeExp", color='country')
app = Dash(__name__)
# App layout
app.layout = html.Div([
dcc.Graph(id='line-graph', figure=fig),
dcc.Graph(id='bar-chart', figure={})
])
@app.callback(
Output("bar-chart", "figure"),
Input("line-graph", "hoverData"),
prevent_initial_call=True
)
def update_markers(hover_data):
print("we want to extract the curveNumber to get the country from the country_index_list")
print(hover_data)
trace = hover_data['points'][0]['curveNumber']
country_hovered = country_index_list[trace]
dff = df[df.country==country_hovered]
fig_bar = px.bar(dff, x='year', y='gdpPercap', title=dff.country.unique()[0])
return fig_bar
# Run the app
if __name__ == "__main__":
app.run_server(debug=True)
If you’re really keen on doing it with the legend, try to replace the callback above with this callback below, and play around with the legend_data argument to extract the values you need.
@app.callback(
Output("bar-chart", "figure"),
Input("line-graph", "restyleData"),
prevent_initial_call=True
)
def update_markers(legend_data):
print(legend_data)
# return empty graph for now until we understand how to extract the clicked legend information we need.
return {}