[Python] Plotly 시각화 마스터: 범례, 템플릿, Pandas 백엔드
Plotly 마스터하기: 디테일과 편의성 잡기
지난 포스팅들에서는 그래프를 그리고 축을 다루는 법을 익혔다. 오늘은 시각화의 완성도를 높여주는 범례(Legend)와 템플릿(Template), 그리고 Pandas에서 Plotly를 바로 쓸 수 있게 해주는 Backend 설정까지 실습해봤다.
데이터는 중고차 가격 데이터인 bmw.csv를 사용했다.
1. 데이터 준비
import pandas as pd
import plotly.express as px
bmw = pd.read_csv("bmw.csv")
# 데이터 확인
print(bmw.shape)
print(bmw['model'].unique()[:5])
모델(model)과 변속기(transmission) 종류에 따른 가격 차이를 시각화해보자. 먼저 집계 데이터를 만든다.
# 각 모델/변속기별 평균 가격 집계
average_prices = bmw.groupby(['model', 'transmission'])['price'].mean().reset_index()
2. 범례(Legend) 커스터마이징
기본 범례는 오른쪽에 위치하지만, 그래프 공간을 넓게 쓰거나 디자인 요소를 더하고 싶을 때 위치를 바꿀 수 있다. update_layout의 legend 속성을 건드리면 된다.
fig = px.bar(average_prices, x='model', y='price', color='transmission', title='모델 변속기별 평균 가격')
# 그래프 레이아웃 상세 항목 설정
fig.update_layout(
xaxis_title='자동차 모델',
yaxis_title='평균 가격',
# 범례 커스텀
legend_title='변속기',
legend_orientation="h", # 가로(Horizontal) 배치
legend_yanchor="bottom",
legend_y=1.1, # 그래프 상단 바깥으로 이동
legend_xanchor="left",
legend_x=0.6,
legend_bgcolor="LightGray", # 배경색
legend_bordercolor="Gray", # 테두리 색
legend_borderwidth=2
)
fig.show()
legend_orientation="h": 범례를 가로로 눕혀서 상단이나 하단에 배치할 때 유용하다.legend_x,legend_y: 좌표값(0~1 정규화 좌표)을 이용해 아주 세밀한 위치 조정이 가능하다.
3. 템플릿(Template) 적용: 분위기 반전
Plotly는 잘 만들어진 내장 테마(Template)를 제공한다. template 인자 하나만 바꿔도 그래프의 느낌이 확 달라진다.
3.1 ggplot2 스타일
R의 시각화 라이브러리인 ggplot2 스타일이다. 회색 격자 배경이 특징이다.
fig = px.bar(
average_prices, x='model', y='price', color='transmission',
title='모델 변속기별 평균 가격_ggplot2',
template="ggplot2" # 템플릿 적용
)
# 레이아웃 설정 (범례 우측 배치)
fig.update_layout(
legend_orientation="v",
legend_x=1.02 # 그래프 오른쪽 바깥
)
fig.show()
3.2 Dark 모드
어두운 배경의 대시보드에 넣을 때 딱이다.
fig = px.bar(
average_prices, x='model', y='price', color='transmission',
title='모델 변속기별 평균 가격_dark',
template="plotly_dark" # 다크 모드 적용
)
# 레이아웃 설정 (Navy 배경 범례)
fig.update_layout(
legend_bgcolor="Navy",
legend_bordercolor="DarkGray",
legend_borderwidth=2
)
fig.show()
4. Pandas Plotly Backend: 생산성의 혁명
이게 오늘 실습의 하이라이트다. Pandas의 기본 .plot()은 matplotlib 기반이라 인터랙티브하지 않다. 하지만 백엔드만 바꿔주면?
# 백엔드 설정: 이제부터 Pandas plot은 Plotly로 그려진다
pd.options.plotting.backend = 'plotly'
# groupby 후 바로 plot() 호출
fig = bmw.groupby('model')['price'].mean().plot(
kind='bar',
title='Pandas Backend로 그린 그래프'
)
fig.show()
import plotly.express를 안 해도 되고, px.bar(df, ...)처럼 인자를 따로 넘길 필요도 없다. 그냥 익숙한 Pandas 문법 뒤에 .plot()만 붙이면 줌, 팬, 툴팁이 되는 Plotly 그래프가 튀어나온다. EDA(탐색적 데이터 분석) 단계에서 엄청나게 편하다.
5. 정리
오늘은 시각화의 디테일과 편의성을 챙기는 팁들을 정리했다.
| 기능 | 속성/코드 | 용도 |
|---|---|---|
| 범례 방향 | legend_orientation="h" |
가로 배치 (공간 효율) |
| 범례 위치 | legend_x, legend_y |
미세한 위치 조정 |
| 범례 스타일 | legend_bgcolor/border |
배경색 및 테두리 |
| 템플릿 | template="..." |
ggplot2, plotly_dark, seaborn 등 테마 적용 |
| 백엔드 설정 | pd.options.plotting.backend = 'plotly' |
Pandas 문법으로 Plotly 사용 |
특히 Pandas Backend 설정은 실무에서 정말 유용하게 쓸 것 같다. 간단한 확인용 그래프는 이걸로, 보고서용 고퀄리티 그래프는 graph_objects로 그리는 전략으로 가야겠다.
Reference
- Data: BMW Used Car Sales(https://www.kaggle.com/datasets/ayeshaimran1619/bmw-sales-and-pricing-trends)
댓글남기기