1. 현재 matplotlib가 사용하는 font의 family와 size 확인하기.
matplotlib의 rcParams (runtime config parameters)에서 확인 가능함.
import matplotlib as mpl
print(f"font.family: {mpl.rcParams['font.family']}"),
print(f"font.size : {mpl.rcParams['font.size']}")
2023.7.12 당시 colab의 경우, 다음과 같은 결과가 나옴.
font.family: ['sans-serif']
font.size : 10.0
2. 현재 matplotlib가 사용가능한 font들 확인하기.
matplotlib의 font_manager를 통해 가능함.
import matplotlib.font_manager as fm # to manage font
# font file들의 경로를 가지는 list 반환.
sys_fonts=fm.findSystemFonts()
print(f"# of sys_font_family : {len(sys_fonts)}")
print(sys_fonts)
# Debian, Ubuntu등에서 사용가능한 Nanum fonts 확인.
nanum_fonts = [f for f in sys_fonts if 'Nanum' in f]
print(f"# of nanum_font family: {len(nanum_fonts)}")
print(nanum_fonts)
# 현재 FontEntry들을 출력 (ttf파일 기준)
ttf_fonts = fm.fontManager.ttflist
print(f"# of ttf_font entries: {len(ttf_fonts)}")
# for f in ttf_fonts:
# print(f.name)
# 현재 Nanum font관련 FontEntry들을 출력 (ttf파일 기준)
# macOS의 AppleGothic이 기본으로 존재하니 'Nanum'대신 이를 'AppleGothic'을 실행.
# windows는 Malgun Gothic 이 기본으로 존재.
nanum_font_entries = [f for f in ttf_fonts if 'Nanum' in f.name]
print(f"# of nanum ttf_font entries: {len(nanum_font_entries)}")
# for f in ttf_fonts:
- colab의 경우, 기본적으로 한글 폰트를 설치해야 한다.
- 때문에, 위의 코드 수행시 설치된 nanum font의 갯수가 0으로 나오는게 정상임.
설치가 되어 있는 경우라면 그냥 다음과 같이 rcParams에서 지정해주면 끝남(Windows와 macOS의 경우)
import matplotlib.pyplot as plt
import platform
# OS에 따라 자동 선택
if platform.system() == 'Windows':
plt.rcParams['font.family'] = 'Malgun Gothic'
elif platform.system() == 'Darwin': # macOS
plt.rcParams['font.family'] = 'AppleGothic'
else: # Linux
plt.rcParams['font.family'] = 'NanumGothic'
plt.rcParams['axes.unicode_minus'] = False
3. Nanum Font 설치하기
3-1. Ubuntu, Debian계열에서 nanum font설치하기.
apt update
apt install fonts-nanum*
# 보단 간단하게는 다음과 같이 설치해도 됨:
# apt -qq -y install fonts-nanum
- Jupyter notebook에서 수행시
!를 앞에 추가해주어야함 (외부 명령어) - 일반적으로는 위의 명령어들을
sudo로 수행시켜야 하나, colab의 경우엔sudo없이 가능.
2023.7.12 당시, 31개의 nanum font들이 설치된다.
- wildcard 문자인 * 를 제외하고 설치시 나눔고딕(fonts-nanum-gothic)과 나눔명조(fonts-nanum-myeongjo)로 구성된 단일 패키지만 설치됨(권장)
system에 nanum font들이 추가설치된 것이지,
matplotlib가 사용가능한 font entry로 추가된 것은 아님.
colab 등의 경우라면, 다음으로 font cache를 삭제하고 kernel을 다시 시작하면 된다.
# 폰트 캐시 삭제
!rm -rf ~/.cache/matplotlib
# # 런타임 재시작
# import os
# os.kill(os.getpid(), 9)
[Linux] Debian 계열 패키지 관리 툴: apt, apt-get
apt (apt-get, apt-cache)apt는Debian 계열의 Linux에서 패키지 관리 SW로서,Package Management System (패키지관리시스템, Package Manager)의High Level Command Line Interface를 제공한다. 달리 말하면 apt-get과 apt-cache와 같은
dsaint31.tistory.com
3-2. macOS에서 Homebrew를 이용한 한글 폰트 설치 및 설정
brew tap homebrew/cask-fonts
brew install --cask font-nanum
brew install --cask font-noto-sans-cjk-kr
font변경이 반영이 안될 경우 다음의 캐시를 삭제하고 다시 시작:
rm -rf ~/Library/Caches/matplotlib
rm -rf ~/.cache/matplotlib
위에서 설치를 언급하긴 했으나, AppleGothic 을 이용하면 되긴 하므로 다음의 설정이면 충분함:
# 1) 한글 지원 폰트 지정 (macOS 기본: AppleGothic / Apple SD Gothic Neo)
# 또는 'Apple SD Gothic Neo', 'NanumGothic', 'Noto Sans CJK KR'
plt.rcParams['font.family'] = 'AppleGothic'
# 2) 마이너스 기호가 네모로 나오는 현상 방지
plt.rcParams['axes.unicode_minus'] = False
macOS는 개인용이므로, 다음과 같이 영구 설정을 하는게 낫다.
~/.config/matplotlib/matplotlibrc (또는 ~/.matplotlib/matplotlibrc)에 다음 추가:
backend: MacOSX
font.family: sans-serif
font.sans-serif: Apple SD Gothic Neo, AppleGothic, NanumGothic, Noto Sans CJK KR
axes.unicode_minus: False
- Apple SD Gothic Neo (1순위 추천)
- macOS 10.8+ 기본 폰트
- 가장 깔끔하고 현대적
- AppleGothic (2순위)
- 구형 macOS 호환용 fallback
- NanumGothic (3순위)
- 별도 설치 필요할 수 있음
- Noto Sans CJK KR (4순위)
- 별도 설치 필요
설정 경로는 다음을 통해 확인 가능:
import matplotlib; print(matplotlib.get_configdir())
3-3. Windows
기본으로 다음의 한글 폰트가 설치되어 있으니 rcParams에 지정만 하면 된다.
- 'Malgun Gothic' : 맑은 고딕
- 'Gulim' : 굴림
- 'Batang' : 바탕
- 'Dotum' : 돋움
- 'Gungsuh' : 궁서
import matplotlib.pyplot as plt
# Windows 기본 한글 폰트 설정
plt.rcParams['font.family'] = 'Malgun Gothic'
plt.rcParams['axes.unicode_minus'] = False
Windows도 개인용일 경우 다음으로 아예 영구 지정하는게 편함.
- C:\Users\사용자명\.matplotlib\ 폴더 생성
- matplotlibrc 파일 생성
다음의 내용을 기재.
backend: TkAgg
font.family: sans-serif
font.sans-serif: Malgun Gothic, Gulim, Dotum
font.serif: Batang, Gungsuh
axes.unicode_minus: False
- Windows에선 backend가 주로 TkAgg이나, macOS에선 MacOSX이고, Linux는 TkAgg 또는 Qt5Agg 임.
- Jupyter/Colab은 inline 혹은 module://matplotlib_inline.backend_inline 임.
4. 한글 위한 FontEntry 생성 및 추가 (수동 추가)
미리 애기하면 이 부분은 기존의 font cache만 제거하면 알아서 이루어지는 과정을 직접 수행해 본 것임.
- 앞서의 각 font cache를 제거하고 다시 시작시키면
- 대부분 matplotlib가 import 될 때 알아서 시스템폰트를 찾음.
수동 추가 방법:
- 앞서
matplotlib.font_manager의sys_fonts를 통해 얻은 한글을 지원하는 nanum font의 ttf 파일 경로 와,matplotlib.font_manager.FontProperties를 통해 ttf파일에서 font 이름을 얻어내고, - 이들을 바탕으로
matplotlib.font_manager.FontEntry객체를 생성한 후, - 생성된
FontEntry객체를matplotlib.font_manager.fontManager.ttflist에 추가한다.
# 1. ttf 파일로부터 font 정보 얻기.
ttf_path = nanum_fonts[0]
font_name = fm.FontProperties(fname=ttf_path, size=10).get_name()
# 2. FontEntry만들기
fe = fm.FontEntry(
fname=ttf_path, # ttf 파일이 저장되어 있는 경로
name=font_name # font_name
)
# 3. matplotlib에 font추가.
fm.fontManager.ttflist.append(fe) # Matplotlib에 폰트 추가
# fm.fontManager.ttflist.insert(0, fe)
mpl.rcParams.update({'font.size': 18, 'font.family': font_name}) # 폰트 설정 (dict의 update임)
ttflist는 Python의 list이며,rcParams는 dictionary임.rcParams는matplotlib.pyplot을 통해서도 접근 가능.
Test
다음 코드는 간단하게 한글이 출력되는지를 확인 가능함.
import matplotlib.pyplot as plt
import numpy as np
data = np.arange(10,30,1)
plt.figure(figsize=(5,4))
plt.plot( data, 'ok')
plt.title('한글 테스트')
plt.ylabel('y축')
plt.xlabel('x축')
plt.show()
결과는 다음과 같음.

중요: axes.unicode_minus 설정
참고로, label에서 nanum font 사용시 minus기호가 깨진다.
이를 제대로 출력하기 위해선 다음의 설정이 필요하다.
mpl.rcParams['axes.unicode_minus'] = False
gist url
https://gist.github.com/dsaint31x/537f27ec5506e7c539279a5c2c472405
py_matplotlib_korean_font_colab.ipynb
py_matplotlib_korean_font_colab.ipynb. GitHub Gist: instantly share code, notes, and snippets.
gist.github.com
참고자료
matplotlib 버전이 올라가서 아래 url대로 하면 동작이 안된다. 하지만 기본적인 내용은 같고 이 문서 보다 자세한 설명이 되어 있어서 첨부한다. (font_manager._rebuild 에서 에러가 남.)
korean_font_on_matplotlib.ipynb
Run, share, and edit Python notebooks
colab.research.google.com
local장비에서 특별히 설치 등을 하지 않고 처리할 때는 기존 한글 폰트를 사용하면 됨.
https://mydevjourney.tistory.com/79
[Python] Matplotlib Mac, Window 한글 깨짐
import matplotlib # windows의 경우 matplotlib.rcParams['font.family'] = 'Malgun Gothic' # mac의 경우 matplotlib.rcParams['font.family'] = 'AppleGothic' 다음의 코드를 운영체제에 맞게 실행해주면 해결된다.
mydevjourney.tistory.com
runtime config parameter들에 대한 참고 자료.
https://jrc-park.tistory.com/274
matplotlib의 구조와 rcParams에 대해 알면 나도 plot 고수 📈
Matplot의 구조 📈 데이터를 시각화 하기 위해서 Matplotlib을 자주 사용합니다. 대부분의 사용자들이 세부적인 구조를 알지 못해 디버깅을 하는데 많은 시간을 소요하게 됩니다. 이번 포스팅에서는
jrc-park.tistory.com
2025.09.20 - [CE] - Font: TTF vs. OTF
Font: TTF vs. OTF
개발자 친화적인 아이콘을 font로 제공하는 Nerd Fonts에서는 아직까지 TTF만을 지원할 정도로, 아직까지는 TTF가 터미널 및 IDE에서는 가장 안정적으로 동작한다. 하지만, 프로그램 라이브러리의 resou
ds31x.tistory.com
2023.07.20 - [Python/matplotlib] - [matplotlib] : backend 란
[matplotlib] : backend 란
matplotlib: backend란 matplotlib의 backend 관련자료를 정리한 문서임.Matplotlib ArchitectureMatplotlib 아키텍트는 다음과 같이 크게 3가지 레이어로 구성된다.Backend Layer :상위 layer에서 graph를 생성하는데 초점
ds31x.tistory.com
'Python > matplotlib' 카테고리의 다른 글
| [matplotlib] : backend 란 (0) | 2023.07.20 |
|---|---|
| [matplotlib]: Figure and Axes (0) | 2023.07.20 |
| [Python] matplotlib : Axis Scale and Ticks (1) | 2023.07.14 |
| [matplotlib] : Styling Artists and Labeling Plots (0) | 2023.07.14 |
| [matplotlib] 계층구조 및 Container : Figure, Axes, Axis (0) | 2023.07.14 |