[Plotly] Dropdown Menus

2022. 2. 4. 19:15개인 공부 공간/Visualization

최근에 plotly를 이용한 시각화를 진행하면서 plotly의 interactive한 특징일 이용하여 대시보드처럼 드롭다운 메뉴를 추가해보고 싶다는 생각이 들었다. 공식 문서를 찾아보니 plotly의 fig.update_layoutupdatemenus를 이용하여 드롭다운 메뉴 추가가 가능해서 이를 코드로 구현해보았다.

고객 정보와 관련된 데이터셋을 활용하여 시각화 하였고, 데이터셋은 아래와 같은 정보를 포함하고 있다.

data.head()

위의 데이터셋에서 Year_Birth 컬럼을 이용해 연령대 컬럼인 Age_Group을 생성하였다.

# 나이 컬럼 생성
data['Age'] = 2022 - data['Year_Birth'] - 1

# 연령대 컬럼 생성
def age_band(x):
    if x < 20:
        return 'under 20'
    elif x < 30:
        return '20s'
    elif x < 40:
        return '30s'
    elif x < 50:
        return '40s'
    elif x < 60:
        return '50s'
    elif x < 70:
        return '60s'
    else:
        return '70_and_over'

data['Age_Group'] = data['Age'].apply(age_band)

 

이후 Age_Group을 이용하여 연령대별 구매 폼목에 대한 시각화를 드롭박스 메뉴와 함께 진행하였다.

product_df = data[['Age_Group', 'MntWines', 'MntFruits', 'MntMeatProducts', 'MntFishProducts', 'MntSweetProducts', 'MntGoldProds']]
grouped_product_df = product_df.groupby('Age_Group').agg('sum').reset_index()
age_group_list = sorted(list(grouped_product_df['Age_Group']))

fig = go.Figure()

buttons = []
age_group_names = []

default_age_group = '20s'

for age in age_group_list:
    temp = grouped_product_df[grouped_product_df['Age_Group'] == age]
    globals()['product_{}'.format(age)] = temp.T.iloc[1:,:].reset_index()
    globals()['product_{}'.format(age)]['index'] = ['Wines', 'Fruits', 'Meat', 'Fish', 'Sweet', 'Gold']
    globals()['product_{}'.format(age)].columns = ['Product_type', 'Purchase_Amt']

    fig.add_trace(go.Bar(x=globals()['product_{}'.format(age)]['Product_type'],
                         y=globals()['product_{}'.format(age)]['Purchase_Amt'],
                         width=0.7,
                         visible=(age==default_age_group),
                         marker_color=colormap))
    
    age_group_names.extend([age])

for age in age_group_list:
    buttons.append(dict(method='update',
                        label=age,
                        args=[{'visible': [age==a for a in age_group_names]}]))

fig.update_layout(paper_bgcolor="rgb(50,50,50,50)", plot_bgcolor="rgb(50,50,50,50)",
                  title_text='Purchase Amount By Merchandise Type',
                  width=800,height=600,
                  font=dict(
                         family="Ubuntu Mono",
                         color='white',
                         size=18),
                  hoverlabel=dict(
                         bgcolor="white",
                         font_size=16,
                         font_family="Ubuntu Mono"),
                  updatemenus=[{'buttons': buttons,
                                'direction': 'down',
                                'active': age_group_list.index(default_age_group),
                                'showactive': True,
                                'x': 1.0,
                                'y': 1.15}]
                 )
fig.show()

 

시각화를 진행한 결과는 아래와 같으며 드롭박스 메뉴를 직접 클릭해보는 기능은 직접 작성한 캐글 노트북 링크에서 확인이 가능하다.

 

이번 시각화를 진행하면서 'plotly가 생각보다 많은 기능을 제공한다는 점'과 '드롭박스 같은 필터링은 기존 대시보드 BI 툴들을 사용하자'라는 생각이 들었다.

물론 한번 코드를 잘 작성해두면 파이썬으로 바로 기능을 구현해볼 때 가끔은 사용할 것 같다는 생각이 들었다.


References

출처: https://privatedevelopnote.tistory.com/81 [개인노트]