logo

플롯 커스터마이제이션

Figure, Axes, Axis의 관계

  • Figure (fig): 캔버스 전체, 차트의 모든 요소를 담는 최상위 컨테이너.
  • Axes (ax): 실제 데이터가 그려지는 플롯 하나. (x축, y축, 제목 등 포함).
  • Axis: 축 하나 (x-axis, y-axis).

Figure와 Axes 생성

# 가로 8, 세로 4 크기의 Figure 생성
fig, ax = plt.subplots(figsize=(8, 4))

# 생성된 Axes(ax)에 seaborn 그래프 그리기
sns.histplot(data=df, x='price', bins=20, kde=True, ax=ax)

제목 및 축 라벨

  • 한글 폰트 설정:
    plt.rcParams['font.family'] = 'Malgun Gothic' # 윈도우의 경우
    plt.rcParams['axes.unicode_minus'] = False # 마이너스 기호 깨짐 방지
    
  • 제목 및 라벨 지정:
    ax.set_title('자동차 가격 분포')
    ax.set_xlabel('가격')
    ax.set_ylabel('빈도')
    

Subplots (여러 그래프 그리기)

  • 하나의 Figure에 여러 개의 Axes를 배치.
# 1행 2열로 Axes 배치
fig, axs = plt.subplots(nrows=1, ncols=2, figsize=(12, 4))

# axs[0]: 첫 번째 그래프, axs[1]: 두 번째 그래프
sns.histplot(data=df, x='price', bins=20, kde=True, ax=axs[0])
sns.boxplot(data=df, x='price', ax=axs[1])

설명 추가 (Text Annotations)

  • 텍스트 추가: ax.text(x, y, '내용', ...)
  • 화살표와 설명 추가: ax.annotate(...)
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': '->'})

범례 (Legend)

  • 그래프의 범례 위치 및 제목 설정.
  • 위치: 'best', 'upper right', 'lower left' 등.
ax.legend(title='모델', loc='lower right')

스타일 (Style)

  • matplotlib의 스타일 시트 사용.
  • plt.style.use('스타일이름')
plt.style.use('dark_background') # 어두운 배경
plt.style.use('default') # 기본값 복구
  • 사용 가능한 스타일 확인: plt.style.available

그림 저장 (Saving)

  • fig.savefig('파일명')
    • PNG 저장: fig.savefig('chart.png')
    • PDF 저장: fig.savefig('chart.pdf')
    • 해상도 지정: dpi=300
    • 투명 배경: transparent=True
Previous
두 변수의 관계 시각화