Post

(python) pyplot.matplotlib

matplotlib

그래프를 그리는 라이브러리다. matplotlib의 pyplot모듈을 이용한다. 룩이 좀 구리지만 기능 자체는 꽤 쓸만하다.

x값 만들기
1
2
3
4
5
6
7
8
9
10
x = np.arange(1, 7, 1) # 1부터 7까지 1의 간격으로 숫자 생성.
[1 2 3 4 5 6]
x = np.arange(1, 7, 2)
[1 3 5]

x = np.linspace(1, 6, 6) # 1부터 6까지를 동일한 간격으로 6개의 값으로 나눈다.
[1. 2. 3. 4. 5. 6.]
x = np.linspace(1, 6, 5)
[1.   2.25   3.5    4.75    6.  ]

2차원 좌표평면값 만들기
1
2
3
4
5
6
7
8
9
## (-1,-1) (-1, -0.99)...(-1, 4) (-0.99, -1) ... (4, 4) 좌표를 먼저 준비한다.
range\_x1 = np.arange(-1, 4, 1)
range\_x2 = np.arange(-1, 4, 1)
xv, yv = np.meshgrid(range\_x1, range\_x2)
## method 1
for i in range(5):
for j in range(5):
print("({}, {})".format(xv[i, j], yv[i, j]), end="")

1
2
(-1, -1)(0, -1)(1, -1)(2, -1)(3, -1)(-1, 0)(0, 0)(1, 0)(2, 0)(3, 0)(-1, 1)(0, 1)(1, 1)(2, 1)(3, 1)(-1, 2)(0, 2)(1, 2)(2, 2)(3, 2)(-1, 3)(0, 3)(1, 3)(2, 3)(3, 3)

1
2
3
4
5
6
## method 2
xv\_col = xv.reshape(xv.size, -1)
yv\_col = yv.reshape(yv.size, -1)
a = np.hstack((xv\_col, yv\_col))
print(a)

1
2
3
4
## method 3 제일 간단하다.
b = np.column\_stack((xv.ravel(), yv.ravel()))
print(b)

1
2
3
4
5
6
7
8
9
[[-1 -1]
[ 0 -1]
[ 1 -1]
[ 2 -1]
[ 3 -1]
[-1  0]
...

예제 1 : sin
1
2
3
4
5
6
7
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 6, 0.1)
y = np.sin(x)
plt.plot(x, y)    # 또는 여기만 scatter로 바꿔도 된다.
plt.show()

x값은 0부터 6까지 0.1단위로 생성된 값들의 배열이다. [0, 0.1, 0.2 … 5.9] y=sin(x)니까 직관적으로 그냥 대입하면 된다.

예제 2 : sin&cos 및 세부사항 설정
1
2
3
4
5
6
7
8
9
10
11
12
13
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 6, 0.1)
y1 = np.sin(x)
y2 = np.cos(x)
plt.plot(x, y1, label="sin")
plt.plot(x, y2, linestyle="--", label="cos", alpha=0.5) #alpha는 반투명
plt.xlabel("x")
plt.ylabel("y")
plt.title("sin & cos")
plt.legend()    #도표 설명
plt.show()

* 창 여러개 띄우기

이런식으로 하면 창이 두개 떠서 sin과 cos가 다른 창에 그려진다.

1
2
3
4
5
6
7
plt.figure(1)
plt.plot(x, y1, label="sin")
plt.figure(2)
plt.plot(x, y2, linestyle="--", label="cos")
plt.legend()
plt.show()

예제 3 : 이미지
1
2
3
4
5
from matplotlib.image import imread
img = imread('C:\BUM\GIT\Python\DLfromScratch\lena.jpg')
plt.imshow(img)
plt.show()

예제 4 : 히스토그램
1
2
3
4
5
6
7
8
9
for i, a in activations.items():
plt.subplot(1, len(activations), i+1)
plt.title(str(i+1) + "-layer")
if i != 0: plt.yticks([], [])
## plt.xlim(0.1, 1)
## plt.ylim(0, 7000)
plt.hist(a.flatten(), 30, range=(0,1))
plt.show()

한글 지원

분명 OS에는 폰트 설치했는데 matplotlib이 폰트를 못찾아서 한글이 다 □ 로 깨져나올 때가 있다. 이는 matplotlib의 fontlist json 파일이 갱신 되지 않아서 그런 것. rebuild 해주면 해결된다.

1
2
3
4
5
>>> from matplotlib import font\_manager
>>> font\_manager.\_rebuild()
>>> for i in font\_manager.fontManager.ttflist:
...     print(i.name, i.fname)

This post is licensed under CC BY 4.0 by the author.