시작하기무료로 시작하기

호버 시 핵심 통계 생성하기

최근 전자상거래 회사의 관리자에게 작업을 시연한 뒤, 그 이해관계자를 위한 대시보드를 만들어 달라는 요청을 받았어요. 너무 많은 시각화와 텍스트는 절대 허용되지 않아요.

대신, 대시보드는 높은 상호작용성을 갖춰야 합니다. 산점도 위에 마우스를 올리면 오른쪽 텍스트 박스에 추가 핵심 통계를 보여 달라고 요청했습니다. 이는 산점도의 다른 점 위로 마우스를 옮길 때마다 변경되어야 합니다.

이 연습은 강의의 일부입니다

Dash와 Plotly로 대시보드 만들기

강의 보기

연습 안내

  • 아래 8번째 줄의 산점도 custom_data 매개변수에 'Country' 열을 추가해 hoverData 속성에 나타나도록 하세요.
  • 아래 28번째 줄에 콜백을 만들어 scatter_fig 그래프와 text_output 요소를 연결하고, 산점도에서 마우스를 올렸을 때 트리거되도록 하세요.

실습형 인터랙티브 연습

이 예제를 이 샘플 코드를 완성하여 풀어보세요.

from dash import Dash, dcc, html, Input, Output, callback
import plotly.express as px
import pandas as pd
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()

app.layout = [
  html.Img(src=logo_link, style={'margin':'30px 0px 0px 0px' }),
  html.H1('Sales breakdowns'),
  html.Div([
    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([
    html.H2('Key Stats'),
    html.P(id='text_output', style={'width':'500px', 'text-align':'center'})],
    style={'width':'700px', 'height':'650px','display':'inline-block'})
]

# Trigger callback on hover
@callback(
    Output('text_output', 'children'),
    ____('scatter_fig', '____'))

def get_key_stats(hoverData):
    if not hoverData:
        return 'Hover over a country to see key stats'
    country = hoverData['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']
    stats_list = [
      f'Key stats for : {country}', html.Br(),
      f'The most popular Major Category by sales volume was: {top_major_cat}', html.Br(),
      f'The highest sales value month was: {top_sales_month}'
    ]
    return stats_list

if __name__ == '__main__':
    app.run(debug=True)
코드 편집 및 실행