본문 바로가기

Python_Intermediate/Matplotilb

Python Matplotlib - 가로 막대 그래프 기초 3(다중 막대 그래프)

반응형

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]

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


3. Sample Code

from matplotlib import pyplot
import numpy

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]

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

pyplot.rcParams["font.family"] = 'Malgun Gothic'
pyplot.rcParams["font.size"] = 12
pyplot.rcParams["figure.figsize"] = (12, 8)

pyplot.figure()

y = numpy.arange(len(label))

pyplot.barh(y-0.2, Daedeok, label='대덕구', height=0.4, color='#ff6600')
pyplot.barh(y+0.2, Donggu, label='동구', height=0.4, color='#0066ff')
pyplot.yticks(y, label)

pyplot.legend()
pyplot.ylabel('월')
pyplot.xlabel('교통사고 수')
pyplot.xlim(0, 150)
pyplot.title('2016년 대덕구/동구 월별 교통사고')

pyplot.savefig('t2.png')

pyplot.close()


4. Sample Code 풀이

- 한글 폰트 전역 설정

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

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

pyplot.rcParams["font.size"] = 12

- 차트의 크기 전역 설정

pyplot.rcParams["figure.figsize"] = (12, 8)

- 그래프 설정 시작

pyplot.figure()

- 기준축에 대한 좌표 배열 생성

y = numpy.arange(len(label))

- 기준측의 좌표와 굵기를 설정 / numpy를 사용하여 연산을 수행

pyplot.barh(y-0.2, Daedeok, label='대덕구', height=0.4, color='#ff6600')
pyplot.barh(y+0.2, Donggu, label='동구', height=0.4, color='#0066ff')

- 좌표에 지정될 라벨 설정

pyplot.yticks(y, label)

- 범주 표시

pyplot.legend()

- 기준축( Y 축) 라벨 설정

pyplot.ylabel('월')

- 데이터축( X 축) 라벨 설정

pyplot.xlabel('교통사고 수')

- 데이터축 범위 설정

pyplot.xlim(0, 150)

- 그래프 제목

pyplot.title('2016년 대덕구/동구 월별 교통사고')

- 출력물 파일 지정

pyplot.savefig('t2.png')

- 그래프 종료

pyplot.close()


5. 출력물


반응형