Hi all
I’m fairly new to Dash and I’m currently learning how to connect 2 graphs together through hover action.
The code below produces 2 graphs; 1 bar graph for sum of sales by country and 1 line graph for daily sales. The line graph displays the daily sales for all countries by default and when a country is hovered over on the bar chart the line graph updates to only show that country’s data.
The problem is that when I “unhover” and move the mouse away from the country, the line graph doesn’t go back to the default state and always shows the data for the last country hovered over.
Setting clear_on_unhover=True in the graph property is supposed to do what I’m looking for but it doesn’t and I appreciate it if someone could help me figure it out what’s wrong with my code.
Screenshots provided under the code
import dash
from dash import html
from dash import dcc
import plotly.express as px
import pandas as pd
from dash.dependencies import Input, Output
sales_df = pd.read_excel('ecom_sales.xlsx')
sales_by_country_df = sales_df.groupby('Country', as_index=False)['OrderValue'].sum()
sales_country_bar_graph = px.bar(sales_by_country_df, x='Country', y='OrderValue', text_auto=True)
app = dash.Dash(__name__)
app.layout = html.Div(children=[
dcc.Graph(id='bar_graph', figure=sales_country_bar_graph),
dcc.Graph(id='line_graph', clear_on_unhover=True)
])
@app.callback(Output('line_graph', 'figure'),
Input('bar_graph', 'hoverData'))
def update_line(hoverData):
if hoverData is None:
all_countries_time_series_df = sales_df.groupby('InvoiceDate', as_index=False)['OrderValue'].sum()
return px.line(all_countries_time_series_df, x='InvoiceDate', y='OrderValue')
else:
country = hoverData['points'][0]['x']
single_country_time_series_df = sales_df[sales_df['Country']== country]
ecom_sales_line_country = single_country_time_series_df.groupby('InvoiceDate', as_index=False)['OrderValue'].sum()
return px.line(ecom_sales_line_country, x='InvoiceDate', y='OrderValue')
if __name__ == "__main__":
app.run_server(debug=True)
When the app first runs
After hovering over
After hovering off, the graph doesn’t update