강의자료 · 인공지능응용

목차

목차

Matplotlib

import numpy as np
import matplotlib.pyplot as plt

1 그래프

# 그래프로 그릴 점들의 
# x좌표 값들과 y좌표 값들을 변수에 넣는다
x = np.arange(0, 3 * np.pi, 0.1)
y = np.sin(x)
# plot함수를 이용해 점들을 그래프로 그린다
plt.plot(x, y)
# 그려진 그래프를 화면에 표시
plt.show()
x = np.arange(0, 3 * np.pi, 0.1)
y_sin = np.sin(x)
y_cos = np.cos(x)
# 그래프 초기화
plt.clf()
plt.plot(x, y_sin)
plt.plot(x, y_cos)
# 축이름 표시
plt.xlabel('x axis')
plt.ylabel('y axis')
# 제목 표시
plt.title('Sine and Cosine')
# 범주 표시 - 리스트를 이용
# 리스트 크기는 그래프 개수와 같아야 함
plt.legend(['Sine', 'Cosine'])
plt.show()

2 다중 그래프

plt.clf()
# 그래프 간격 조절
left=0.0
bottom=0.0
right=1.0
top=1.0
wspace=1.0
hspace=1.0
plt.subplots_adjust(left, bottom, right, top, wspace, hspace)
# 세로로 2개, 가로로 1개의 그래프 배치 선언
# 그중 1번에 그래프 생성
plt.subplot(2,1,1)
plt.plot(x,y_sin)
plt.title('Sine')
plt.xlabel('x axis')
plt.ylabel('y axis')
# 2번에 그래프 생성
plt.subplot(2,1,2)
plt.plot(x,y_cos)
plt.title('Cosine')
plt.xlabel('x axis')
plt.ylabel('y axis')
plt.show()

3 텍스트 작업

plt.clf()
plt.plot(x, y_sin)
plt.plot(x, y_cos)
plt.xlabel('x axis')
plt.ylabel('y axis')
plt.title('Sine and Cosine')
plt.legend(['Sine', 'Cosine'])
# text(a,b,s) : a, b 위치에 텍스트 s 출력
plt.text(4,0.5, 'here!')
# 텍스트로 수식 표현
plt.text(6,0.5,r'$y=sin(x)$')
plt.show()
plt.clf()
plt.plot(x, y_sin)
plt.plot(x, y_cos)
plt.xlabel('x axis')
plt.ylabel('y axis')
plt.title('Sine and Cosine')
plt.legend(['Sine', 'Cosine'])
plt.annotate('min', xy=(np.pi, -1), xytext=(5, -0.5), 
             arrowprops=dict(facecolor='black', shrink=0.05),)
plt.show()

4 실습