본문 바로가기

Programming/Python

pandas 로 엑셀 파일 읽어올 때 한글이 깨질 경우, 한글 폰트 세팅하기

반응형

안녕하세요. 명동섞어찌개 입니다.

오늘은 파이썬에서 pandas 를 사용해 엑셀을 읽어오고, matplotlib 를 사용해서 그래프를 그릴 때 한글이 깨지는 문제 해결 방법을 가이드 하려고 합니다. (참고로 저는 Mac 에서 사용했습니다. )

그냥 matplotlib 를 사용해서 데이터를 읽어오면 아래와 같이 보입니다. 

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

data = pd.read_excel('../../issues_en.xlsx')

.
.
.
(이하 코드 생략)

한글이 깨져보임 ㅠㅠㅠ

 

이 문제를 해결하려고 여기 저기 블로그에 나온 방법들을 검색해서 따라해봤지만 한번에 해결되지는 않았습니다 ㅠ 제가 해결한 방법도 완벽하지는 않겠지만 공유하려고 합니다. 

 

1. font_manager , rc 를 임포트합니다.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import font_manager, rc 

 

2. 컴퓨터의 폰트 경로와 이름을 찍어봅니다.

font_list = font_manager.findSystemFonts(fontpaths=None, fontext='ttf')
font_list[:10]

 이건 font_list 중에 상위 10개만 찍어본 건데요, 저의 경우 다음과 같이 찍혔습니다.

['/usr/share/fonts/stix/STIX-Regular.otf',
 '/usr/share/fonts/NanumFont/NanumGothicBold.ttf',
 '/usr/share/fonts/NanumFont/NanumGothicExtraBold.ttf',
 '/usr/share/fonts/stix/STIX-Bold.otf',
 '/usr/share/fonts/NanumFont/NanumGothic.ttf',
 '/usr/share/fonts/NanumFont/NanumPen.ttf',
 '/usr/share/fonts/NanumFont/NanumMyeongjoBold.ttf',
 '/usr/share/fonts/stix/STIX-BoldItalic.otf',
 '/usr/share/fonts/NanumFont/NanumMyeongjoExtraBold.ttf',
 '/usr/share/fonts/NanumFont/NanumMyeongjo.ttf']

 

여기서 사용할 폰트의 '경로/이름'을 통째로 복사해 줍니다.

 

3. 사용할 폰트 경로를 세팅해줍니다.

위에서 복사한 폰트 경로를 아래와 같이 써주면 됩니다. 

font_name = font_manager.FontProperties(fname="/usr/share/fonts/NanumFont/NanumGothic.ttf").get_name()
rc('font', family=font_name)

 

이렇게 하고 다시 코드를 돌리니 한글이 잘 나왔습니다!!

업무에 조금 도움이 되었으면 합니다. 

 

 

 

 

참고한 사이트

http://corazzon.github.io/matplotlib_font_setting