파이썬
[matplotlib] local 로컬에서 custom font, 원하는 ttf 파일 사용하기
mcdn
2023. 6. 15. 13:53
반응형
1. 폰트 다운받기 : wget and unzip font zipfile
!wget http://cdn.naver.com/naver/NanumFont/fontfiles/NanumFont_TTF_ALL.zip
!mkdir NanumFont
%cd NanumFont
!unzip ../NanumFont_TTF_ALL.zip
%cd ..
jupyter notebook에서 쉘 실행할거면 zip 파일 다운로드 그리고 unzip해야한다.
2. 폰트 추가하기 Add font to matplotlib's font_manager
import matplotlib.pyplot as plt
from matplotlib import font_manager, rc
path_font = 'NanumFont/NanumGothic.ttf'
# Create a Matplotlib Font object from our `.ttf` file
font = font_manager.FontEntry(fname=str(path_font), name="Nanum Gothic")
# Register this object with Matplotlib's ttf list
font_manager.fontManager.ttflist.append(font)
# Print the last few items to see what they look like
print(font_manager.fontManager.ttflist[-1:])
print 결과
[FontEntry(fname='NanumFont/NanumGothic.ttf', name='Nanum Gothic', style='normal', variant='normal', weight='normal', stretch='normal', size='medium')]
3. 폰트 matplotlib rcParams에 추가하기
from matplotlib import rcParams
rcParams['font.family'] = 'Nanum Gothic'
rcParams['font.family']에 아까 등록한 name 으로 추가하면 된다.
4. 마지막으로 plt~ 코드실행
import matplotlib.pyplot as plt
from matplotlib import rcParams
rcParams['font.family'] = 'Nanum Gothic'
# Plotting the class distribution for train dataset
plt.figure(figsize=(10, 4))
plt.subplot(1, 3, 1)
train_class_counts.plot(kind='bar')
plt.xlabel('Classes')
plt.ylabel('Count')
plt.title('Train Class Distribution')
마지막으로 원하는 코드를 실행하면 한글이 나온다!
참고:
https://towardsdatascience.com/matplotlib-and-custom-fonts-bee4aac7b5cb
Matplotlib and Custom Fonts
A More Definitive Guide
towardsdatascience.com
반응형