플롯 커스터마이제이션
Figure, Axes, Axis의 관계
- Figure (fig): 캔버스(액자) 전체. 차트의 모든 요소를 담는 가장 큰 단위.
- Axes (ax): 실제 데이터가 그려지는 하나의 플롯 공간
- x축(Axis), y축(Axis), 제목, 플롯 자체를 모두 포함.
- Axis: 하나의 축 (x-axis, y-axis).
- 가로 8, 세로 4 크기의 Figure 생성
fig, ax = plt.subplots(figsize=(8, 4))
- 생성된 Axes에 시본으로 그래프 그리기
sns.histplot(data=df, x='price', bins=20, kde=True, ax=ax)
- 시본으로 그래프를 그리면, 그려진 Axes를 반환
ax = sns.histplot(data=df, x='price', bins=20, kde=True)
제목 및 축 라벨
plt.rcParams['font.family'] = 'Malgun Gothic' # 맑은 고딕으로 글꼴 설정
plt.rcParams['axes.unicode_minus'] = False # 마이너스 기호 깨짐 방지
ax = sns.histplot(data=df, x='price', bins=20, kde=True)
ax.set_title('자동차 가격 분포') # 그래프 제목
ax.set_xlabel('가격') # x축 레이블 설정
ax.set_ylabel('빈도') # y축 레이블 설정
하나의 Figure에 여러 Axes
# 하나의 Figure에 1행 2열로 Axes를 배치
fig, axs = plt.subplots(nrows=1, ncols=2, figsize=(12, 4))
sns.histplot(data=df, x='price', bins=20, kde=True, ax=axs[0]) # 0번 Axes
sns.boxplot(data=df, x='price', ax=axs[1]) # 1번 Axes
설명 추가
ax = sns.scatterplot(data=df, x='year', y='price', hue='model')
ax.text(2010, 1200, '★2010년', fontsize=12, color='red')
ax.annotate('600만원', xy=(2013, 600), xytext=(2016, 400),
arrowprops={'facecolor': 'black', 'arrowstyle': '->'},
fontsize=10, color='red')
범례
ax = sns.scatterplot(data=df, x='year', y='price', hue='model')
ax.legend(title='모델', loc='lower right')
- 위치:
- 'best' (기본값, 자동으로 최적 위치 선정)
upper left upper center upper right
center left center center right
lower left lower center lower right
스타일
- 어두운 배경 스타일로 그리기
plt.style.use('dark_background')
ax = sns.scatterplot(data=df, x='year', y='price', hue='model')
- 기본 스타일
plt.style.use('default')
- 가능한 스타일 목록:
plt.style.available
그림 저장
fig.savefig('chart_name.png') # PNG 파일로 저장
fig.savefig('chart_name.pdf') # PDF 파일로 저장, 벡터
fig.savefig('high_res.png', dpi=300) # 해상도(dpi) 지정
fig.savefig('transparent.png', transparent=True) # 배경 투명
- ax만 있을 경우에는 ax.figure로 그림에 접근할 수 있음
ax.figure.savefig('chart_name.png')
퀴즈
사용자 정보 입력
퀴즈를 시작하기 전에 이름과 소속을 입력해주세요.