반응형
matplotlib에서 한글깨지는 현상 해결하기¶
In [1]:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# 한글폰트 적용을 위해 필요한 library
import matplotlib as mpl
import matplotlib.font_manager as fm
from matplotlib import rc
import warnings
warnings.filterwarnings(action='ignore') # 경고 무시
# 그래프에서 '-' 기호가 문제가 생길 수 있음
mpl.rcParams['axes.unicode_minus'] = False
한글 폰트 파일이 필요하다.
ttf파일을 사용가능한 위치에 저장하고 불러온다.
In [2]:
font_path = './font/malgun.ttf'
font_name = fm.FontProperties(fname=font_path).get_name()
print(font_name)
rc('font', family=font_name)
Malgun Gothic
Data Load
In [3]:
df = pd.read_excel('./data/lineplot_sample_data.xlsx') # 1970년부터 2022년까지의 지역별 인구 이동 수
df = df.fillna(method='ffill')
seoul_df = df[(df['전출지별']=='서울특별시') & (df['전입지별'] != '서울특별시')]
seoul_df.drop('전출지별', axis=1, inplace=True)
seoul_df.rename({'전입지별' : '전입지'}, axis=1, inplace=True)
seoul_df.set_index('전입지', inplace=True)
s = seoul_df.loc['경기도']
In [4]:
plt.figure(figsize=(20,6)) # figsize(가로크기, 세로크기), inch 단위
plt.title('서울특별시에서 경기도로의 전입 인구 추이')
plt.plot(s.index, s.values)
plt.xlabel('년도')
plt.ylabel('이동인구수')
plt.margins(x=0)
plt.show()
한글이 잘 적용되는 것을 확인 할 수 있다.
추가 : 그래프 꾸미기¶
- 그래프 크기 : figure(figsize=(가로크기, 세로크기) inch 단위
- 스타일 적용 : style.use(스타일명)
- x축 레이블 회전 : xticks(rotation='x')
In [5]:
# 그래프에 스타일 적용하기
plt.figure(figsize=(15,5)) # figsize(가로크기, 세로크기)
plt.margins(x=0)
##### 스타일 #####
plt.style.use('ggplot')
##### x축 레이블 회전 #####
plt.xticks(rotation='vertical')
plt.plot(s.index, s.values,
marker='o',
markersize = 5,
markerfacecolor = 'g',
color = 'g',
linewidth = 2)
# circle marker : o, square marker : s, point marker,,,
# r : red, g : green, y : yellow
plt.title('서울특별시에서 경기도로의 전입 인구 추이')
plt.xlabel('년도')
plt.ylabel('이동인구수')
plt.legend(labels=['서울 -> 경기'], loc = 'best') # 범례
plt.show()
반응형
'Programming > Data Visualize' 카테고리의 다른 글
[matplotlib] line plot, scatter plot, box plot 그리기 & subplot을 이용해 그래프 여러 개 그리기 (0) | 2022.03.22 |
---|