matplotlib 사용법

예제 1: 액시즈를 이용한 플랏

- 구조 : axis $\subset$ axes $\subset$ figure

import matplotlib.pyplot as plt
fig = plt.figure() # 도화지를 준비한다. 
<Figure size 432x288 with 0 Axes>
fig # 현재 도화지상태를 체크 
<Figure size 432x288 with 0 Axes>

- 그림객체를 출력해봐야 아무것도 나오지 않는다. (아무것도 없으니까)

fig.add_axes() # fig에 액시즈를 추가 
fig.axes # 현재 fig에 있는 액시즈 정보
fig.axes # 현재 fig에 있는 액시즈 정보
[]
fig.add_axes([0,0,1,1]) 
<Axes:>

도화지안에 (0,0) 위치에 길이가 (1,1) 인 네모틀을 만듦

fig.axes # 현재 네모틀 상태를 체크 -> 네모틀이 하나 있음.
[<Axes:>]
fig # 현재 도화지 상태 체크 -> 도화지에 (하나의) 네모틀이 잘 들어가 있음 
axs1=fig.axes[0] ## 첫번째 액시즈 
axs1.plot([1,2,3],'or:') # 첫번째 액시즈에 접근하여 그림을 그림 
[<matplotlib.lines.Line2D at 0x19a41260d00>]
fig #현재 도화지 상태 체크 --> 그림이 잘 그려짐 

예제2: 액시즈를 이용한 서브플랏 (방법1)

fig # 현재 도화지 출력

- 액시즈추가

fig.add_axes([1,0,1,1])
# 1,0 위치에 길이 1,1 짜리 틀 추가
<Axes:>
fig.axes
[<Axes:>, <Axes:>]
fig
axs2=fig.axes[1] ## 두번째 액시즈 

- 두번째 액시즈에 그림그림

axs2.plot([1,2,3],'ok') ## 두번째 액시즈에 그림그림 
[<matplotlib.lines.Line2D at 0x19a413bdfd0>]
fig ## 현재 도화지 체크

- 첫번째 액시즈에 그림추가

axs1.plot([1,2,3],'--') ### 액시즈1에 점선추가 
[<matplotlib.lines.Line2D at 0x19a413bd460>]
fig ## 현재 도화지 체크 

예제3: 액시즈를 이용하여 서브플랏 (방법2)

fig = plt.figure() 
# 새로운 도화지
<Figure size 432x288 with 0 Axes>
fig.axes
[]
fig.subplots(1,2)
# default는 1,1
array([<AxesSubplot:>, <AxesSubplot:>], dtype=object)
fig.axes
[<AxesSubplot:>, <AxesSubplot:>]
ax1,ax2 = fig.axes
ax1.plot([1,2,3],'or')
ax2.plot([1,2,3],'ob')
[<matplotlib.lines.Line2D at 0x19a416ba820>]
fig
fig.set_figwidth(12)
# 도화지 늘려보자
fig
ax1.plot([1,2,3],'--')
[<matplotlib.lines.Line2D at 0x19a413341c0>]
fig

예제4: 액시즈를 이용하여 2$\times$2 서브플랏 그리기

fig = plt.figure()
fig.axes
[]
<Figure size 432x288 with 0 Axes>
fig.subplots(2,2) 
fig.axes
[<AxesSubplot:>, <AxesSubplot:>, <AxesSubplot:>, <AxesSubplot:>]
ax1,ax2,ax3,ax4=fig.axes 
ax1.plot([1,2,3],'ob')
ax2.plot([1,2,3],'or')
ax3.plot([1,2,3],'ok')
ax4.plot([1,2,3],'oy')
[<matplotlib.lines.Line2D at 0x19a417ffd60>]
fig

예제5: plt.subplots()를 이용하여 2$\times$2 서브플랏

x=[1,2,3,4]
y=[1,2,4,3]
_, axs = plt.subplots(2,2) 
axs[0,0].plot(x,y,'o:r') 
axs[0,1].plot(x,y,'Xb') 
axs[1,0].plot(x,y,'xm') 
axs[1,1].plot(x,y,'.--k') 
[<matplotlib.lines.Line2D at 0x19a41aab370>]

주의

x=[1,2,3,4]
y=[1,2,4,3]
_, axs = plt.subplots(2,2) 
axs[0,0].plot(x,y,'o:r') 
axs[0,1].plot(x,y,'Xb') 
axs[1,0].plot(x,y,'xm') 
axs[1,1].plot(x,y,'.--k') 
[<matplotlib.lines.Line2D at 0x19a43184370>]
_

예제6: plt.subplots()를 2$\times$2 subplot 그리기 - 액시즈를 각각 변수명으로 저장

x=[1,2,3,4]
y=[1,2,4,3]
fig, axs = plt.subplots(2,2) 
axs
# 중첩 리스트 형태로 들어가있음
array([[<AxesSubplot:>, <AxesSubplot:>],
       [<AxesSubplot:>, <AxesSubplot:>]], dtype=object)

중첩리스트 형태라

ax1,ax2,ax3,ax4 =axs

이렇게하면 error


(ax1,ax2), (ax3,ax4) = axs
ax1.plot(x,y,'o:r') 
ax2.plot(x,y,'Xb') 
ax3.plot(x,y,'xm') 
ax4.plot(x,y,'.--k') 
[<matplotlib.lines.Line2D at 0x23b4236a880>]
fig

예제7: plt.subplots()를 이용하여 2$\times$2 서브플랏 그리기 - fig.axes에서 접근

fig, _ = plt.subplots(2,2)
fig.axes
[<AxesSubplot:>, <AxesSubplot:>, <AxesSubplot:>, <AxesSubplot:>]
ax1, ax2, ax3, ax4= fig.axes
ax1.plot(x,y,'o:r') 
ax2.plot(x,y,'Xb') 
ax3.plot(x,y,'xm') 
ax4.plot(x,y,'.--k') 
[<matplotlib.lines.Line2D at 0x19a435783d0>]
fig

title 설정

예제1: plt.plot()

x=[1,2,3]
y=[1,2,2]
plt.plot(x,y,'o:k')
plt.title('fuck')
Text(0.5, 1.0, 'fuck')

예제2: 액시즈를 이용

기본적으로 1개 설정됨

fig = plt.figure()
fig.subplots()
<AxesSubplot:>
ax1=fig.axes[0]
ax1.set_title('title')
Text(0.5, 1.0, 'title')
fig

예제3: subplot에서 각각의 제목설정

fig, ax = plt.subplots(2,2) 
axs
array([[<AxesSubplot:>, <AxesSubplot:>],
       [<AxesSubplot:>, <AxesSubplot:>]], dtype=object)
(ax1,ax2),(ax3,ax4) =ax
ax1.set_title('title1')
ax2.set_title('title2')
ax3.set_title('title3')
ax4.set_title('title4')
Text(0.5, 1.0, 'title4')
fig
fig.tight_layout() # 암기 
fig

예제4 : 액시즈의 제목 + Figure제목

슈퍼타이틀=도화지 전체의 제목 명명

fig.suptitle('sup title')
Text(0.5, 0.98, 'sup title')
fig
fig.tight_layout()
fig

그냥 x=[1,2,3]만 입력해주면 (1,1)(2,2)(3,3)으로 값 설정됨

x=[1,2,3]
y=[4,5,6]
plt.plot(x,y,'o')
[<matplotlib.lines.Line2D at 0x19a43700430>]

축 범위 재조정 中

plt.plot(x,y,'o')
plt.xlim(-1,5)
plt.ylim(3,7)
(3.0, 7.0)

예제2

fig = plt.figure()
fig.subplots()
<AxesSubplot:>
ax1=fig.axes[0]
import numpy as np 
ax1.plot(np.random.normal(size=100),'o')
[<matplotlib.lines.Line2D at 0x19a437edf40>]
fig
ax1.set_xlim(-10,110)
ax1.set_ylim(-5,5)
(-5.0, 5.0)
fig

예제1

np.linspace(-1,1,100,endpoint=True)

= start는 배열 시작값, stop은 배열의 끝 값, num은 start와 stop사이를 몇 개의 일정한 간격으로 요소를 만들 것인지, 만일 num을 생략하면 디폴트로 50개의 수열을 만들며, 마지막 endpoint가 의미하는 것은 stop으로 주어진 값을 포함시킬 것인지 아닌지를 선택하는 옵션

np.random.seed(43052)
x1=np.linspace(-1,1,100,endpoint=True)
y1=x1**2+np.random.normal(scale=0.1,size=100)
axs1=plt.plot(x1,y1,'o:m')
axs1=plt.title('y=x**2')
np.corrcoef(x1,y1)
array([[1.        , 0.00688718],
       [0.00688718, 1.        ]])
  • 상관계수의 값이 0에 가까운 것은 두 변수의 직선관계가 약한것을 의미하는 것, 두 변수 사이에 아무런 함수관계가 없다는 것을 의미하는 것은 아니다.

예제2

- 아래와 같은 자료를 고려하자.

np.random.seed(43052)
x2=np.random.uniform(low=-1,high=1,size=100000)
y2=np.random.uniform(low=-1,high=1,size=100000)
axs2=plt.plot(x2,y2,'.')
axs2=plt.title('rect')
np.corrcoef(x2,y2)
array([[1.        , 0.00521001],
       [0.00521001, 1.        ]])

예제3

np.random.seed(43052)
_x3=np.random.uniform(low=-1,high=1,size=100000)
_y3=np.random.uniform(low=-1,high=1,size=100000)
plt.plot(_x3,_y3,'.')
[<matplotlib.lines.Line2D at 0x19a44dae280>]
radius = _x3**2+_y3**2 
x3=_x3[radius<1]
y3=_y3[radius<1]
plt.plot(_x3,_y3,'.')
plt.plot(x3,y3,'.')
[<matplotlib.lines.Line2D at 0x19a44e281f0>]
axs3=plt.plot(x3,y3,'.')
axs3=plt.title('circ')
np.corrcoef(x3,y3)
array([[ 1.        , -0.00362687],
       [-0.00362687,  1.        ]])