Generate key stats on hover
After a recent demonstration of your work to a manager in the e-commerce company, you have received a request to create a dashboard for this stakeholder. Having too many visualizations and too much text is absolutely not allowed.
Instead, they want the dashboard to be highly interactive. They have requested a scatter plot that, when hovered over, will provide some additional key stats in a text box to the right. This should change when hovering over a new point on the scatter plot.
This exercise is part of the course
Building Dashboards with Dash and Plotly
Exercise instructions
- Add the country column to the scatter plot's
custom_data
below line11
so it will show up in thehoverData
property of the figure and can be used in a callback. - Create a callback below line
40
that will be triggered by hovering over the scatter plot. - Extract the custom data you included in the scatter plot's hover data below line
50
. - Use the aggregated variables created for you on lines
54
(top_major_cat
) and55
(top_sales_month
) to create a list of text data below line57
to be used in the output of the callback.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
import dash
from dash import dcc, html
import plotly.express as px
import pandas as pd
from dash.dependencies import Input, Output
ecom_sales = pd.read_csv('/usr/local/share/datasets/ecom_sales.csv')
logo_link = 'https://assets.datacamp.com/production/repositories/5893/datasets/fdbe0accd2581a0c505dab4b29ebb66cf72a1803/e-comlogo.png'
ecom_country = ecom_sales.groupby('Country')['OrderValue'].agg(['sum', 'count']).reset_index().rename(columns={'count':'Sales Volume', 'sum':'Total Sales ($)'})
# Add the country data to the scatter plot
ecom_scatter = px.scatter(ecom_country, x='Total Sales ($)', y='Sales Volume',
color='Country', width=350, height=400, ____=['____'])
ecom_scatter.update_layout({'legend':dict(orientation='h', y=-0.5,x=1, yanchor='bottom', xanchor='right'), 'margin':dict(l=20, r=20, t=25, b=0)})
app = dash.Dash(__name__)
app.layout = html.Div([
html.Img(src=logo_link,
style={'margin':'30px 0px 0px 0px' }),
html.H1('Sales breakdowns'),
html.Div(
children=[
html.Div(
children=[
html.H2('Sales by Country'),
dcc.Graph(id='scatter_fig', figure=ecom_scatter)
],
style={'width':'350px', 'height':'500px', 'display':'inline-block',
'vertical-align':'top', 'border':'1px solid black', 'padding':'20px'}),
html.Div(
children=[
html.H2('Key Stats'),
html.P(id='text_output', style={'width':'500px', 'text-align':'center'}),
],
style={'width':'700px', 'height':'650px','display':'inline-block'}),
]),],
style={'text-align':'center', 'display':'inline-block', 'width':'100%'})
# Trigger callback on hover
@app.callback(
Output('text_output', 'children'),
____('scatter_fig', '____'))
def get_key_stats(hoverData):
if not hoverData:
return 'Hover over a country to see key stats'
# Extract the custom data from the hoverData
country = ____['points'][0]['customdata'][0]
country_df = ecom_sales[ecom_sales['Country'] == country]
top_major_cat = country_df.groupby('Major Category').agg('size').reset_index(name='Sales Volume').sort_values(by='Sales Volume', ascending=False).reset_index(drop=True).loc[0,'Major Category']
top_sales_month = country_df.groupby('Year-Month')['OrderValue'].agg('sum').reset_index(name='Total Sales ($)').sort_values(by='Total Sales ($)', ascending=False).reset_index(drop=True).loc[0,'Year-Month']
# Use the aggregated variables
stats_list = [
f'Key stats for : {country}', html.Br(),
f'The most popular Major Category by sales volume was: {____}', html.Br(),
f'The highest sales value month was: {____}'
]
return stats_list
if __name__ == '__main__':
app.run_server(debug=True)