데이터 분석
Matplotlib의 모든 것
핸들이없는8톤트럭
2022. 8. 15. 22:30
반응형
Matplotlib
출판 가능한 품질로 다양한 그림을 그려주는 오픈소스 파이썬 패키지입니다. 상호작용이 가능하며, 다양한 플랫폼으로 출력할 수 있습니다. 이름에서 알 수 있듯이, matlab에서의 그림과 비슷한 그림을 그려줍니다!
matplotlib을 이용한 자료의 시각화
matplotlib의 계층 체계
- figure : 그림이 완성되어 그려지는 한 단위
- axe : 그림을 그리는 단위공간으로, 하나의 figure에 여러 개의 axe가 존재할 수 있습니다.
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0.0,1.0,10)
y = x**2
plt.figure(figsize=(4,3))
plt.plot(x,y,'r-')
plt.show()
plt.figure(figsize=(4,3))
plt.plot(x,y,'ro-',
markersize=10,
markerfacecolor='black',
markeredgecolor=(0,0,1), # (R,G,B)
markeredgewidth=2,
linewidth=5,
antialiased=False, # 주위와 구분이 잘되게끔 색깔의 구분이 뚜렷한게 하는 기능
label = '$x^2$') # 달러 표시 안쪽에는 수식 입력 가능
plt.legend()
plt.show()
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0.0,1.0,10)
y = x ** 2
fig = plt.figure(figsize=(4,3))
ax = fig.subplots()
ax.plot(x,y,'r-')
plt.show()
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0.0,1.0,10)
y = x ** 2
fig = plt.figure()
ax1 = fig.add_axes((0.1,0.1,0.8,0.8)) # *(x, y, width, height)
ax2 = fig.add_axes((0.2,0.5,0.4,0.3))
ax1.plot(x,y,'b-')
ax1.set_title('Larger plot')
ax2.plot(y,x,'r-')
ax2.set_title('smaller plot')
plt.show()
fig=plt.figure()
ax1, ax2 = fig.subplots(nrows=2,ncols=1) # (행,열)
ax1.plot(x,y,'b-')
ax2.plot(y,x,'r-')
plt.show()
하나의 axe에 여러 plot 그리기
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0.0,1.0,10)
y = x **2
fig = plt.figure()
ax = fig.subplots()
ax.plot(x,y,'b-',label='$x^2$')
ax.plot(y,x,'r-',label='$sqrt(x)$')
ax.legend()
plt.show()
scatter plot
import numpy as np
import matplotlib.pyplot as plt
x= np.random.randn(50)
y= np.random.randn(50)
fig = plt.figure(figsize=(4,3))
ax = fig.subplots()
ax.scatter(x,y,
marker='^',
c=x+y,
cmap='magma', # color map https://matplotlib.org/stable/tutorials/colors/colormaps.html
alpha=0.5,
label='samples')
ax.grid() # 격자 무늬를 그려줌
ax.set_xlim(-4,4) #x축 범위 설정
ax.set_ylim(-4,4)
ax.set_xticks([-3,-2,-1,0,1,2,3])
ax.set_yticks([-3,-2,-1,0,1,2,3])
ax.legend(loc='upper left', fontsize=20) #upper right / bottom left / bottom right / best
ax.set_title('Scatter is cool',fontsize=22)
ax.set_xlabel('x')
ax.set_ylabel('y',rotation=0)
fig.savefig('pic.png',dpi=200)
plt.show()
반응형