IT일지/파이썬

[파이썬] matplotlib 차트 제목에 한글 출력하기

체험가 2024. 2. 14. 13:43
반응형

matplotlib로 차트를 그리는데 제목과 x, y 축 라벨에 한글을 넣어서 실행했더니 발생한 경고문입니다.

 

아래는 테스트 코드입니다.

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

# 날짜 생성
dates = pd.date_range(start='2024-01-01', end='2024-01-31')

# 랜덤 데이터 생성
data = np.random.randint(50, 150, size=len(dates))

# 그래프 그리기
plt.figure(figsize=(10, 6))
plt.plot(dates, data, marker='o', linestyle='-')

plt.title('제목')
plt.xlabel('날짜')
plt.ylabel('값')
plt.tight_layout()
plt.show()

 

위 코드를 실행하면 아래와 같은 경고가 발생합니다.

UserWarning: Glyph 44288 (\N{HANGUL SYLLABLE NAL}) missing from current font.

 

실행 결과를 봐도

 

이렇게 한글이 깨져서 출력됩니다.


해결방법

해당 문제는 pc에 matplotlib에서 사용할 수 있는 한글 폰트가 제대로 설치되어있지 않은 경우 발생한다고 합니다.

 

import matplotlib.font_manager

fonts = matplotlib.font_manager.findSystemFonts(fontpaths=None, fontext='ttf')
for font in fonts:
    print(font)

설치된 폰트 확인용 코드

 

위 코드를 실행하면

matplotlib에서 사용할 수 있는 폰트 리스트를 출력할 수 있습니다.

 

폰트 리스트에서 한글과 관련된 폰트가 없으면 한글 폰트를 설치하고 아래와 같이 코드를 수정합니다.

폰트 설치방법은 윈도우10 폰트 설치하기에서 확인할 수 있습니다.

from matplotlib.font_manager import FontProperties

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

# 날짜 생성
dates = pd.date_range(start='2024-01-01', end='2024-01-31')

# 랜덤 데이터 생성
data = np.random.randint(50, 150, size=len(dates))

# 그래프 그리기
plt.figure(figsize=(10, 6))
plt.plot(dates, data, marker='o', linestyle='-')

font_path = 'C:\\Windows\\Fonts\\NanumGothic.ttf'
font_prop = FontProperties(fname=font_path)

plt.title('제목', fontproperties = font_prop)
plt.xlabel('날짜', fontproperties = font_prop)
plt.ylabel('값', fontproperties = font_prop)
plt.tight_layout()
plt.show()

font_path에는 한글 폰트를 설치한 다음 위에 설치된 폰트 확인용 코드를 실행해서 한글 폰트 경로를 복사한 다음 붙여넣으면 됩니다.

 

 

실행해보면

 

한글이 깨지지 않고 정상적으로 출력되는 것을 알 수 있습니다.

728x90
반응형