Python에서 시각화 작업을 하다보면 한글이 깨지는 문제가 종종 발생하게 된다. 그럴 때마다 검색해서 해결하는 일이 반복되어, 이번에 한글 폰트 설치부터 적용, 그리고 폰트의 경로를 지정하여 불러오는 방법을 정리해두고자 한다. 그리고 특정 부분만 폰트를 다르게 설정하는 방법도 기록해두고자 한다.
최근에 matplotlib를 이용하여 이미지 파일 생성 자동화하면서, 알게된 몇 가지 팁도 함께 정리하고자 한다.
1. 한글 글꼴 깨짐 문제 해결
matplotlib를 기본 설정으로 실행하면 한글을 제대로 표시하지 못한다. 이를 해결하려면 한글 글꼴을 설치해야 한다. 나는 나눔고딕(NanumGothic)을 설치했다.
# 한글 폰트 설치
!apt -qq -y install fonts-nanum > /dev/null
설치 후 바로 rcParams에 적용하면 되는 경도 있지만, 나는 적용이 되지 않아 설치된 경로를 직접 확인하고 지정해주었다.
- 설치된 폰트 경로 확인
!fc-list | grep -i nanum
예시 출력:
/usr/share/fonts/truetype/nanum/NanumSquareRoundB.ttf: NanumSquareRound,나눔스퀘어라운드,NanumSquareRound Bold,나눔스퀘어라운드 Bold:style=Bold,Regular
/usr/share/fonts/truetype/nanum/NanumGothicCodingBold.ttf: NanumGothicCoding,나눔고딕코딩:style=Bold
/usr/share/fonts/truetype/nanum/NanumSquareRoundR.ttf: NanumSquareRound,나눔스퀘어라운드,NanumSquareRound Regular,나눔스퀘어라운드 Regular:style=Regular
/usr/share/fonts/truetype/nanum/NanumSquareB.ttf: NanumSquare,나눔스퀘어,NanumSquare Bold,나눔스퀘어 Bold:style=Bold
/usr/share/fonts/truetype/nanum/NanumBarunGothic.ttf: NanumBarunGothic,나눔바른고딕:style=Regular
/usr/share/fonts/truetype/nanum/NanumGothic.ttf: NanumGothic,나눔고딕:style=Regular
/usr/share/fonts/truetype/nanum/NanumGothicCoding.ttf: NanumGothicCoding,나눔고딕코딩:style=Regular
/usr/share/fonts/truetype/nanum/NanumBarunGothicBold.ttf: NanumBarunGothic,나눔바른고딕:style=Bold
/usr/share/fonts/truetype/nanum/NanumGothicBold.ttf: NanumGothic,나눔고딕:style=Bold
/usr/share/fonts/truetype/nanum/NanumSquareR.ttf: NanumSquare,나눔스퀘어:style=Regular
/usr/share/fonts/truetype/nanum/NanumMyeongjo.ttf: NanumMyeongjo,나눔명조:style=Regular
/usr/share/fonts/truetype/nanum/NanumMyeongjoBold.ttf: NanumMyeongjo,나눔명조:style=Bold
이제 경로를 이용하여 matplotlib에 직접 폰트를 적용해준다.
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
# 폰트 경로 등록
font_path = "/usr/share/fonts/truetype/nanum/NanumGothic.ttf"
fm.fontManager.addfont(font_path)
# 폰트 설정
plt.rcParams['font.family'] = 'NanumGothic'
plt.rcParams['axes.unicode_minus'] = False
2. 특정 텍스트만 다른 글꼴 적용하기
전체 그래프에는 나눔고딕을 쓰되, 특정 텍스트만 굵게 적용하고 싶을 때는 FontProperties를 활용할 수 다.
from matplotlib.font_manager import FontProperties
# 나눔고딕 Bold 경로 지정 및 적용
font_bold_path = "/usr/share/fonts/truetype/nanum/NanumGothicBold.ttf"
bold_font = FontProperties(fname=font_bold_path)
# 예시
plt.figure(figsize=(6, 4))
plt.text(0.5, 0.7, '기본 나눔고딕입니다', ha='center', va='center', fontsize=14)
plt.text(0.5, 0.4, '이건 나눔고딕 Bold!', ha='center', va='center', fontsize=14, fontproperties=bold_font)
plt.show()
plt.text()에 fontproperties 인자를 지정하면 해당 텍스트만 별도의 스타일을 적용할 수 있다.
3. 표 시각화 예시
나의 예제는 다음과 같다. matplotlib의 table 기능을 활용해 표를 만들고, 헤더에만 굵은 글씨와 배경색을 적용했다.
이때, .set_fontproperties(bold_font) 를 이용했다.
font_path = "/usr/share/fonts/truetype/nanum/NanumGothic.ttf"
font_bold_path = "/usr/share/fonts/truetype/nanum/NanumGothicBold.ttf"
fm.fontManager.addfont(font_path)
fm.fontManager.addfont(font_bold_path)
# 전역 설정
plt.rcParams['font.family'] = 'NanumGothic'
plt.rcParams['axes.unicode_minus'] = False
# 특정 셀에 적용할 굵은 글꼴 속성
bold_font = fm.FontProperties(fname=font_bold_path)
# 시각회
fig, ax = plt.subplots(figsize=(6, 2.5)
ax.axis('off')
table = ax.table(
cellText=sub_df.values,
colLabels=sub_df.columns,
loc='center',
cellLoc='center'
)
# 첫 행(헤더)만 강조 (굵은 글씨 + 배경색)
for col_idx in range(len(df.columns)):
cell = table[0, col_idx]
cell.get_text().set_fontproperties(bold_font)
cell.set_facecolor('#d0f0c0')
plt.tight_layout()
plt.savefig("table_with_bold_header.png", dpi=300)
plt.close()
이렇게 하면 표의 첫 번째 행(헤더)에만 굵은 글씨체와 배경색을 지정할 수 있다.
마무리
- matplotlib에서 한글이 깨질 땐, 직접 폰트를 설치하고 경로를 지정해주는 것이 가장 확실하다.
- 부분적으로 폰트를 바꾸고 싶을 땐, FontProperties를 이용하면 유연하게 스타일을 지정할 수 있다.
- 표 시각화 시, 특정 셀에만 스타일을 자유롭게 설정할 수 있다. (글씨체, 배경색)
'파이썬' 카테고리의 다른 글
[파이썬][pandas/datetime] 날짜형 변환 (데이터프레임) (1) | 2024.10.11 |
---|---|
[python] 문자열 나누기 : split() 함수와 구분자의 활용 (1) | 2024.09.21 |
[python] If문 간결하게 작성하는 방법 : 코드 가독성 높이기 (0) | 2024.09.12 |
[파이썬/python] strip 함수 - 공백 제거, 특정 문자 제거 (0) | 2024.09.05 |
[python][데이터처리] 공백으로 채워진 값을 null로 바꾸기 (0) | 2024.07.21 |