본문 바로가기

Python_Intermediate/Matplotilb

Python Matplotlib - 선 그래프 한글 폰트 적용

반응형

1. 그래프 단계(셀로판지 개념)

1단계 : 배경 설정(축)

2단계 : 그래프 추가(점, 막대, 선)

3단계 : 설정 추가(축 범위, 색, 표식)


2. Sample Data Base

Daedeok = [81, 70, 94, 91, 74, 78, 80, 81, 75, 89, 102, 110]
Donggu = [84, 82, 86, 89, 75, 91, 100, 88, 108, 111, 88, 77]
Seogu = [199, 173, 159, 190, 190, 194, 173, 207, 189, 188, 223, 218]
Yuseong = [122, 114, 154, 157, 171, 151, 160, 139, 138, 177, 178, 154]
Junggu = [98, 96, 105, 121, 128, 109, 102, 116, 109, 119, 108, 102]


3. Sample Label Data Base

label = ['1월', '2월', '3월', '4월', '5월', '6월', '7월', '8월', '9월', '10월', '11월', '12월']


4. Sample Code

from matplotlib import pyplot

Daedeok = [81, 70, 94, 91, 74, 78, 80, 81, 75, 89, 102, 110]
Donggu = [84, 82, 86, 89, 75, 91, 100, 88, 108, 111, 88, 77]
Seogu = [199, 173, 159, 190, 190, 194, 173, 207, 189, 188, 223, 218]
Yuseong = [122, 114, 154, 157, 171, 151, 160, 139, 138, 177, 178, 154]
Junggu = [98, 96, 105, 121, 128, 109, 102, 116, 109, 119, 108, 102]

label = ['1월', '2월', '3월', '4월', '5월', '6월', '7월', '8월', '9월', '10월', '11월', '12월']

pyplot.rcParams['font.family'] = 'NanumGothic'
pyplot.rcParams['font.size'] = 8

pyplot.figure()

pyplot.grid()

pyplot.title('2016년 대전시 월별 교통사고')
pyplot.xlabel('월')
pyplot.ylabel('교통사고')

pyplot.plot(Daedeok, label='대덕구')
pyplot.plot(Donggu, label='동구')
pyplot.plot(Seogu, label='서구')
pyplot.plot(Yuseong, label='유성구')
pyplot.plot(Junggu, label='중구')

pyplot.xlim(0,11)
pyplot.ylim(0,250)

pyplot.legend(title='구', loc='lower right', shadow=True)

x = list(range(0, len(label)))

pyplot.xticks(x, label)

pyplot.savefig('TrafficAccident.png', dpi=200)


5. Sample Code 풀이

- 한글 폰트 전역 설정

pyplot.rcParams['font.family'] = 'NanumGothic'

- 한글 폰트 사이즈 전역 설정

pyplot.rcParams['font.size'] = 8

- 그래프 설정 시작

pyplot.figure()

- 배경 그리드 표시(격자 표시)

pyplot.grid()

- 그래프 제목 설정

pyplot.title('2016년 대전시 월별 교통사고')

- X 축 라벨 설정

pyplot.xlabel('월')

- Y 축 라벨 설정

pyplot.ylabel('교통사고')

- 라벨 DATA 설정(출력 내역 누적)

pyplot.plot(Daedeok, label='대덕구')
pyplot.plot(Donggu, label='동구')
pyplot.plot(Seogu, label='서구')
pyplot.plot(Yuseong, label='유성구')
pyplot.plot(Junggu, label='중구')

- X 축 범위 설정

pyplot.xlim(0,11)

- Y 축 범위 설정

pyplot.ylim(0,250)

- 범주 표시 설정

pyplot.legend(title='구', loc='lower right', shadow=True)

loc 속성 값

best 

 0 / 최고

upper right

 오른쪽 상단

upper le

 왼쪽 상단

lower right

 오른쪽 하단

lower left

 왼쪽 하단

right

 오른쪽

center left

 센터 왼쪽

center right

 센터 오른쪽 

lower center

 하단 중앙

upper center

 상단 중앙 

center

 중앙


- x 축의 각 지점에 적용될 라벨 리스트설정

x = list(range(0, len(label)))

- 좌표에 지정될 라벨 설정

pyplot.xticks(x, label)

- 파일 저장 및 DPI 설정(기본값 100)

pyplot.savefig('TrafficAccident.png', dpi=200)


6. 출력물


반응형