Programming/Python
Matplotlib 정리
JinWooHong Dev
2020. 7. 21. 17:57
Matplotlib 정리
In [8]:
import matplotlib
In [11]:
%matplotlib inline
# 주피터 노트북에서 실행한 브라우저에서 바로 볼 수 있게 해주는 명령어
In [10]:
import matplotlib.pyplot as plt
plt.plot([1,2,4,9,5,3])
plt.show()
In [13]:
plt.plot([0,-1,-3,0],[0,4,2,4])
plt.show()
plt.axis [xmin, xmax, ymin, ymax]
In [18]:
plt.plot([0,-1,-3,0],[0,4,2,4])
plt.axis([-5,5,-5,5])
plt.show()
np.linspace -2 와 2 사이를 500개 만큼 나눈 값을 반환
In [23]:
import numpy as np
x = np.linspace(-2, 2, 500)
y = x**2
plt.plot(x, y)
plt.show()
타이틀을 추가하고 x와 y 라벨을 넣고 격자(grid)를 넣을 수 있다
In [25]:
plt.plot(x, y)
plt.title("Square function")
plt.xlabel("x")
plt.ylabel("y = x**2")
plt.grid(True)
plt.show()
선 스타일과 색
초기 설정은 선은 실선이다.
In [26]:
plt.plot([0,100,100,0,0,100,50,0,100],[0,0,100,100,0,100,130,100,0])
plt.axis([-10, 110, -10, 140])
plt.show()
In [32]:
plt.plot([0, 100, 100, 0, 0, 100, 50, 0, 100],
[0, 0, 100, 100, 0, 100, 130, 100,0],"g--")
plt.axis([-10, 110, -10, 140])
plt.show()
In [34]:
plt.plot([0, 100, 100, 0, 0], [0, 0, 100, 100, 0], "r-",
[0, 100, 50, 0, 100], [0, 100, 130, 100, 0], "g--")
plt.axis([-10, 110, -10, 140])
plt.show()
In [40]:
plt.plot([0, 100, 100, 0, 0], [0, 0, 100, 100, 0], "r-")
plt.plot([0, 100, 50, 0, 100], [0, 100, 130, 100, 0], "g--")
plt.axis([-10, 110, -10, 140])
plt.show()
선 스타일과 색에 대한 옵션은 https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.plot 을 참고
In [41]:
x = np.linspace(-1.4,1.4,30)
plt.plot(x,x,'g--',x,x**2,'r:',x,x**3,'b^')
plt.show()
선 너비, 대쉬 스타일 또는 투명도 등 추가 속성들이 있다.¶
In [56]:
x = np.linspace(-1.4,1.4,30)
line1, line2, line3 = plt.plot(x, x, 'g--',x, x**2, 'r-.', x, x**3, 'b^')
line1.set_linewidth(5.0)
line1.set_dash_capstyle("round")
line3.set_alpha(0.1)
plt.show()
Figure 저장
In [57]:
x = np.linspace(-1.4, 1.4, 30)
plt.plot(x, x**2)
plt.savefig("my_square_function.png", transparent=True)
Subplots¶
In [59]:
x = np.linspace(-1.4, 1.4, 30)
plt.subplot(2, 2, 1)
plt.plot(x, x)
plt.subplot(2, 2, 2)
plt.plot(x, x**2)
plt.subplot(2, 2, 3)
plt.plot(x, x**3)
plt.subplot(2, 2, 4)
plt.plot(x, x**4)
plt.show()
In [63]:
plt.subplot(2, 2, 1)
plt.plot(x, x)
plt.subplot(2, 2, 2)
plt.plot(x, x**2)
plt.subplot(2, 1, 2)
plt.plot(x, x**3)
plt.show()
더 복잡한 포지셔닝을 원하면 subplot2grid 를 사용하면 된다. 행과 열의 수를 지정하고 행 또는 열 수를 선택적으로 지정 왼쪽 위가 (0,0)
In [78]:
plt.subplot2grid((3,3),(0,0), rowspan=2, colspan=2)
plt.plot(x, x**2)
plt.subplot2grid((3,3),(0,2))
plt.plot(x, x**3)
plt.subplot2grid((3,3,),(1,2),rowspan=2)
plt.plot(x,x**4)
plt.subplot2grid((3,3),(2,0),colspan=2)
plt.plot(x,x**5)
plt.show()
여러가지 Figures
In [105]:
x = np.linspace(-1.4, 1.4, 30)
plt.figure(1)
plt.subplot(211)
plt.plot(x, x**2)
plt.title("Square and Cube")
plt.subplot(212)
plt.plot(x, x**3)
plt.figure(2, figsize=(10,5))
plt.subplot(121)
plt.plot(x, x**4)
plt.title("y = x**4")
plt.subplot(122)
plt.plot(x, x**5)
plt.title("y = x**5")
plt.figure(1)
plt.plot(x,-x**3,"r:") # figure 1 로 돌아온다, 최근 subplot(212)
plt.show()
Pyplot's state machine : implicit vs explicit
In [106]:
import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
In [112]:
x = np.linspace(-2, 2, 200)
fig1, (ax_top, ax_bottom) = plt.subplots(2, 1, sharex=True)
fig1.set_size_inches(10,5)
line1, line2 = ax_top.plot(x, np.sin(3*x**2), "r-", x, np.cos(5*x**2),"b-")
line3 = ax_bottom.plot(x, np.sin(3*x), "r-")
ax_top.grid(True)
fig2, ax = plt.subplots(1,1)
ax.plot(x, x**2)
plt.show()
text 그리기
In [132]:
x = np.linspace(-1.5, 1.5, 30)
px = 0.8
py = px**2
plt.plot(x, x**2, "b-", px, py, "ro")
plt.text(0, 1.5, "Square function\n$y = x^2$",fontsize=20, color='blue',
horizontalalignment="center")
plt.text(px - 0.08, py, "Beautiful point", ha="right", weight="heavy")
plt.text(px, py-0.3, "x= %0.2f\ny=%0.2f"%(px,py),rotation=50,color="gray")
plt.show()
In [137]:
plt.plot(x, x**2, px, py, "ro")
plt.annotate("Beautiful point", xy=(px, py), xytext=(px-1.3, py+0.5),
color="green",weight="heavy", fontsize=14,
arrowprops={"facecolor":"lightgreen"})
plt.show()
In [140]:
plt.plot(x, x**2, px, py, "ro")
bbox_props = dict(boxstyle="rarrow,pad=0.3",ec="b",lw=2,fc="lightblue")
plt.text(px-0.2,py,"Beautiful point",bbox=bbox_props, ha="right")
bbox_props = dict(boxstyle="round4,pad=1,rounding_size=0.2", ec="black", fc="#EEEEFF", lw=5)
plt.text(0, 1.5, "Square function\n$y = x^2$", fontsize=20, color='black', ha="center", bbox=bbox_props)
plt.show()
In [141]:
with plt.xkcd():
plt.plot(x, x**2, px, py, "ro")
bbox_props = dict(boxstyle="rarrow,pad=0.3", ec="b", lw=2, fc="lightblue")
plt.text(px-0.2, py, "Beautiful point", bbox=bbox_props, ha="right")
bbox_props = dict(boxstyle="round4,pad=1,rounding_size=0.2", ec="black", fc="#EEEEFF", lw=5)
plt.text(0, 1.5, "Square function\n$y = x^2$", fontsize=20, color='black', ha="center", bbox=bbox_props)
plt.show()
Legends
In [142]:
x = np.linspace(-1.4, 1.4, 50)
plt.plot(x, x**2, "r--", label="Square function")
plt.plot(x, x**3, "g--", label="Cube function")
plt.legend(loc="best")
plt.grid(True)
plt.show()
Non linear scales
In [144]:
x = np.linspace(0.1, 15, 500)
y = x**3/np.exp(2*x)
plt.figure(1)
plt.plot(x,y)
plt.yscale('linear')
plt.title('linear')
plt.grid(True)
plt.figure(2)
plt.plot(x, y)
plt.yscale('log')
plt.title('log')
plt.grid(True)
plt.figure(3)
plt.plot(x, y)
plt.yscale('logit')
plt.title('logit')
plt.grid(True)
plt.figure(4)
plt.plot(x, y - y.mean())
plt.yscale('symlog', linthreshy=0.05)
plt.title('symlog')
plt.grid(True)
plt.show()
눈금 및 눈금자
In [145]:
x = np.linspace(-2, 2, 100)
plt.figure(1, figsize=(15,10))
plt.subplot(131)
plt.plot(x, x**3)
plt.grid(True)
plt.title("Default ticks")
ax = plt.subplot(132)
plt.plot(x, x**3)
ax.xaxis.set_ticks(np.arange(-2, 2, 1))
plt.grid(True)
plt.title("Manual ticks on the x-axis")
ax = plt.subplot(133)
plt.plot(x, x**3)
plt.minorticks_on()
ax.tick_params(axis='x', which='minor', bottom='off')
ax.xaxis.set_ticks([-2, 0, 1, 2])
ax.yaxis.set_ticks(np.arange(-5, 5, 1))
ax.yaxis.set_ticklabels(["min", -4, -3, -2, -1, 0, 1, 2, 3, "max"])
plt.title("Manual ticks and tick labels\n(plus minor ticks) on the y-axis")
plt.grid(True)
plt.show()
Polar projection
In [149]:
radius = 1
theta = np.linspace(0, 2*np.pi*radius,1000)
plt.subplot(111, projection='polar')
plt.plot(theta, np.sin(5*theta), "g-")
plt.plot(theta, 0.5*np.cos(20*theta), "b-")
plt.show()
3D projection
In [158]:
from mpl_toolkits.mplot3d import Axes3D
x = np.linspace(-5, 5, 50)
y = np.linspace(-5, 5, 50)
X, Y = np.meshgrid(x,y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
figure = plt.figure(1, figsize=(12,4))
subplot3d = plt.subplot(111, projection='3d')
surface = subplot3d.plot_surface(X, Y, Z, rstride=1, cstride=1,
cmap=matplotlib.cm.coolwarm, linewidth=0.1)
plt.show()
In [159]:
plt.contourf(X, Y, Z, cmap=matplotlib.cm.coolwarm)
plt.colorbar()
plt.show()
Scatter plot
In [160]:
from numpy.random import rand
x, y = rand(2, 100)
plt.scatter(x,y)
plt.show()
In [164]:
x, y, scale= rand(3,100)
scale = 500 * scale ** 5
plt.scatter(x,y,s=scale)
plt.show()
In [168]:
for color in ['red','green', 'blue']:
n = 100
x, y = rand(2, n)
scale = 500.0 * rand(n) ** 5
plt.scatter(x,y,s=scale, c=color, alpha=0.5,edgecolors='black')
plt.grid(True)
plt.show()
Lines
In [171]:
from numpy.random import randn
def plot_line(axis, slope, intercept, **kargs):
xmin, xmax = axis.get_xlim()
plt.plot([xmin, xmax], [xmin*slope+intercept, xmax*slope+intercept],
**kargs)
x = randn(1000)
y = 0.5*x + 5 + randn(1000)*2
plt.axis([-2.5, 2.5, -5, 15])
plt.scatter(x, y, alpha=0.2)
plt.plot(1, 0, "ro")
plt.vlines(1, -5, 0, color="red")
plt.hlines(0, -2.5, 1, color="red")
plot_line(axis=plt.gca(), slope=0.5, intercept=5, color="magenta")
plt.grid(True)
plt.show()
히스토그램
In [179]:
data = [1, 1.1, 1.8, 2, 2.1, 3.2, 3, 3, 3, 3]
plt.subplot(211)
plt.hist(data, bins =15, rwidth=0.8)
plt.subplot(212)
plt.hist(data, bins = [1, 1.5, 2, 2.5, 3], rwidth=0.95)
plt.xlabel("Value")
plt.ylabel("Frequency")
plt.show()
In [177]:
data1 = np.random.randn(400)
data2 = np.random.randn(500) + 3
data3 = np.random.randn(450) + 6
data4a = np.random.randn(200) + 9
data4b = np.random.randn(100) + 10
plt.hist(data1, bins=5, color='g', alpha=0.75, label='bar hist') # default histtype='bar'
plt.hist(data2, color='b', alpha=0.65, histtype='stepfilled', label='stepfilled hist')
plt.hist(data3, color='r', histtype='step', label='step hist')
plt.hist((data4a, data4b), color=('r','m'), alpha=0.55, histtype='barstacked', label=('barstacked a', 'barstacked b'))
plt.xlabel("Value")
plt.ylabel("Frequency")
plt.legend()
plt.grid(True)
plt.show()
Images¶
In [181]:
import matplotlib.image as mpimg
img = mpimg.imread('my_square_function.png')
print(img.shape, img.dtype)
(288, 432, 4) float32
In [182]:
plt.imshow(img)
plt.show()
In [185]:
plt.imshow(img)
plt.axis('off')
plt.show()
In [187]:
img = np.arange(100*100).reshape(100,100)
print(img)
plt.imshow(img)
plt.show()
[[ 0 1 2 ... 97 98 99]
[ 100 101 102 ... 197 198 199]
[ 200 201 202 ... 297 298 299]
...
[9700 9701 9702 ... 9797 9798 9799]
[9800 9801 9802 ... 9897 9898 9899]
[9900 9901 9902 ... 9997 9998 9999]]
In [188]:
plt.imshow(img, cmap="hot")
plt.show()
In [213]:
img = np.empty((30,50,3))
img[:10, :] = [0,0,0]
img[10:20,] = [1,0,0]
img[20:,:]=[1,1,0]
plt.imshow(img)
Out[213]:
<matplotlib.image.AxesImage at 0x126f8c810>