python matplotlib.pyplot의 plot와 bar를 사용한 유용한 그래프 그리기 정리
matplotlib는 python에서 matlab과 유사하게 그래프를 그리도록 도와주는
라이브러리다. 다양한 기능이 있지만, 본 포스트에서는 plot와 bar를 사용해 그래프를
그리는 예제를 싣고 있다.
matplotlib.pyplot 불러오기
import matplotlib.pyplot as plt
그래프의 크기 설정
matplotlib.pyplot.figure를 사용해 새로운 figure를 만들어 그래프 크기를
설정할 수도 있고, 아래 코드 처럼 rcParams를 사용해 그래프의 크기를 설정 할
수도 있다.
plt.rcParams['figure.figsize'] = [10,5] #default: [6.4, 4.8]
위 코드는 랜더링 되는 그래프의 크기를 가로 10 inch, 세로 5 inch로 설정한다.
그래프의 타이틀 및 x,y 축 label
그래프의 타이틀은 matplotlib.pyplot.title를 사용해 설정할 수 있으며,
x,y축의 label은 matplotlib.pyplot.xlabel, matplotlib.ylabel을 사용해 설정할 수
있다.
plt.title('my graph')
plt.xlabel('x')
plt.ylabel('y')
plot 사용하여 그래프 그리기
plot는 아래와 같은 형식으로 호출할 수 있다.
matplotlib.pyplot.plot([x], y, [fmt], *, data=None, **kwargs)
matplotlib.pyplot.plot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)
matplotlib.pyplot.plot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)
x 는 x 축의 데이터이고 y 는 y 축 데이터를 의미한다.
'fmt' 설정을 통해 선의 색상과 모양을 설정할 수 있다. 지원되는 format은 아래와
같다.
fmt marker
'.' point marker
',' pixel marker
'o' circle marker
'v' triangle_down marker
'^' triangle_up marker
'<' triangle_left marker
'>' triangle_right marker
'1' tri_down marker
'2' tri_up marker
'3' tri_left marker
'4' tri_right marker
's' square marker
'p' pentagon marker
'*' star marker
'h' hexagon1 marker
'H' hexagon2 marker
'+' plus marker
'x' x marker
'D' diamond marker
'd' thin_diamond marker
'|' vline marker
'_' hline marker
fmt 선 스타일
'-' solid line style
'--' dashed line style
'-.' dash-dot line style
':' dotted line style
fmt 선 색상
'b' blue
'g' green
'r' red
'c' cyan
'm' magenta
'y' yellow
'k' black
'w' white
plot 예제 코드
plt.title('sin/cos')
plt.xlabel('x')
plt.ylabel('y')
plt.plot(x, y1,'-r')
plt.plot(x, y2,'-.g')
plt.show()
plt.title('sin/cos')
plt.xlabel('x')
plt.ylabel('y')
plt.plot(x, y1,'.r',x, y2,'xg')
plt.show()
legend 범례 만들기
범례(legend)는 아래 API를 사용해 생성할 수 있다.
matplotlib.pyplot.legend()
matplotlib.pyplot.legend(labels)
matplotlib.pyplot.legend(handles, labels)
matplotlib.pyplot.legend(labels)
matplotlib.pyplot.legend(handles, labels)
라인의 label을 sinx(x), cos(x)로 설정하고 범례를 표시하도록 한 예제 코드는
아래와 같다.
plt.title('sin/cos')
plt.xlabel('x')
plt.ylabel('y')
plt.plot(x, y1,'-r')
plt.plot(x, y2,'-xg')
plt.legend(('sin(x)','cos(x)'))
plt.show()
legend의 위치는 matplotlib.pyplot.legend의 argument인 loc, bbox_to_anchor등을
통해 설정할 수 있다.
위 예제 코드에서 legend 호출 부분을 아래와 같이 바꾸면 다음 그림과 같이
legend가 그래프 밖에 표시되는 것을 볼 수 있다.
plt.legend(('sin(x)','cos(x)'),loc='upper left',bbox_to_anchor=(1.0, 1))
loc 의 값은 'best', 'upper right', 'upper left', 'lower left', 'lower right',
'right', 'center left', 'center right', 'lower center', 'upper center',
'center' 로 설정할 수 있다.
bbox_to_anchor의 값은 2-tuple, 4-tuple로 설정할 수 있다.
2-tuple인 경우 loc에 지정된 위치의 모서리 (x,y)에 범례가 위치하게 되고,
4-tupe인 경우 범례가 배치되는 위치를 (x,y,width, height)로 설정할 수
있다.
bar를 사용한 그래프 그리기
API는 아래와 같다.
matplotlib.pyplot.bar(x, height, width=0.8, bottom=None, *, align='center',
data=None, **kwargs)
x는 x축 값를 의미하며 문자도 사용할 수 있다. height는 그려질 y축의 값을
의미한다.
bar 사용 예제 코드
plt.title('bar example')
plt.xlabel('x')
plt.ylabel('y')
bar_width = 0.1
plt.bar(x-bar_width/2, y1,width=bar_width,color='blue',label='blue')
plt.bar(x+bar_width/2, y2,width=bar_width,color='red',label='red')
plt.legend(loc='upper left',bbox_to_anchor=(1.0,1.0))
plt.show()
여러 개의 bar를 그릴 경우, 예제 코드처럼 x 값을 조정해 bar가 그려질 위치를
조정할 수 있다.
matplotlib.pyplot.bar의 argument bottom은 bar가 그려질 시작 y 값을 의미하며,
아래 예제 코드와 같이 사용할 수 있다.
x = ['A1','A2','A3','A4','A5']
Bval = [3,1,1,1,1]
Cval = [0.5,2,3,1,3]
plt.title('bar example II')
plt.xlabel('category')
plt.ylabel('Val')
plt.bar(x, Bval,bottom=Cval,width=0.1)
plt.bar(x, Cval,width=0.1)
plt.show()
더 많은 예제와 자료는 아래 사이트에서 찾아볼 수 있다.
댓글
댓글 쓰기