Python
Matplotlib
IT_달토끼
2023. 3. 27. 14:23
Matplotlib는 데이터 시각화를 위한 파이썬 라이브러리이다.
Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python.
Matplotlib makes easy things easy and hard things possible.
Matplotlib를 이용하여 그래프와 이미지를 표시해보자.
1). Sin & Cos 그래프
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, label='cos')
plt.xlabel('X axis')
plt.ylabel('Y axis')
plt.title('sin&cos')
plt.legend()
plt.show()

2) 라인플롯
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 100, 2)
y = x * 2
plt.plot(x, y)
plt.show()

3) 히스토그램
from numpy.random import normal, rand
import matplotlib.pyplot as plt
x = normal(size=100)
plt.hist(x, bins=20)
plt.show()

4) 산점도
from numpy.random import rand
import matplotlib.pyplot as plt
x = rand(100)
y = rand(100)
plt.scatter(x, y)
plt.show()

5) 3D 플롯
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.gca(projection = '3d')
x = np.arange(0, 6, 0.15)
y = np.arange(0, 6, 0.15)
x, y = np.meshgrid(x, y)
r = np.sqrt(x**2 + y**2)
z = np.sin(r)
surf = ax.plot_surface(x, y, z, rstride = 1, cmap = cm.coolwarm)
plt.show()

6) 이미지
import matplotlib.pyplot as plt
img = imread('img.png')
plt.imshow(img)
plt.xlabel('x axis')
plt.ylabel('y axis')
plt.title('landscape')
plt.show()

이외에도 다양한 시각화가 가능하다.
source: matplolib.org, wikipedia