matplotlib 數據可視化
參考資料:https://matplotlib.org/stable/index.html ###
matplotlib.pyplot.cla() & matplotlib.pyplot.clf() &
matplotlib.pyplot.close() matplotlib.pyplot.cla():清除當前座標軸。
matplotlib.pyplot.clf():清除當前圖形。
matplotlib.pyplot.close():關閉整個視窗。 ### 做出一個簡易的一次函數圖形
1
2
3
4
5
6import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-1, 1,50)
y = 2*x+1
plt.plot(x,y)
plt.show()
而若要做出檢簡易的二次函數,則只需更改y的值,將值設為二次方的數字
同時顯示兩個figure
1 | import numpy as np |
plt.figure(num = 3,figsize =
(8,5))裡第一個參數是figure的編號,第二個參數是調整視窗大小,plt.plot()的第一個參數是x座標,第二個參數是y座標,第三個參數是線條顏色,第四個參數是線條寬度,地五個參數是線條外觀。
### subplot()
subplot()的功能就是在同一個figure裡創造子圖,參數可放三個數字,分別代表「列數、行數、圖形編號」。
### 顯示出自己限定的x和y的範圍 1
2
3
4
5
6
7
8
9
10
11import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(3, -3,50)
y1 = 2*x+1
y2 = x**2
plt.figure()
plt.plot(x,y2)
plt.plot(x,y1,color = 'red',linewidth = 1.0,linestyle = '-')
plt.xlim((-1,2))
plt.ylim((-2,3))
plt.show()1
2
3
4
5
6
7
8
9
10
11
12
13import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(3, -3,50)
y1 = 2*x+1
y2 = x**2
plt.figure()
plt.plot(x,y2)
plt.plot(x,y1,color = 'red',linewidth = 1.0,linestyle = '-')
plt.xlim((-1,2))
plt.ylim((-2,3))
plt.xlabel('long')
plt.ylabel('length')
plt.show() ### 更換單位
xticks yticks
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(3, -3,50)
y1 = 2*x+1
y2 = x**2
plt.figure()
plt.plot(x,y2)
plt.plot(x,y1,color = 'red',linewidth = 1.0,linestyle = '-')
plt.xlim((-1,2))
plt.ylim((-2,3))
plt.xlabel('long')
plt.ylabel('length')
new_ticks = np.linspace(-1,2,5)
print(new_ticks)
plt.xticks(new_ticks)
plt.yticks([-2,-1.5,-1,1.2,3],['worst','bad','normal','good','best'])
plt.show() ### 更改字體&特別符號
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(3, -3,50)
y1 = 2*x+1
y2 = x**2
plt.figure()
plt.plot(x,y2)
plt.plot(x,y1,color = 'red',linewidth = 1.0,linestyle = '-')
plt.xlim((-1,2))
plt.ylim((-2,3))
plt.xlabel('long')
plt.ylabel('length')
new_ticks = np.linspace(-1,2,5)
print(new_ticks)
plt.xticks(new_ticks)
plt.yticks([-2,-1.5,-1,1.2,3],[r'$worst$',r'$bad$',r'$\alpha$',r'$good$',r'$best$'])
plt.show()
顯示座標軸
會使用到gca(get current axis) 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(3, -3,50)
y1 = 2*x+1
y2 = x**2
plt.figure()
plt.plot(x,y2)
plt.plot(x,y1,color = 'red',linewidth = 1.0,linestyle = '-')
plt.xlim((-1,2))
plt.ylim((-2,3))
plt.xlabel('long')
plt.ylabel('length')
new_ticks = np.linspace(-1,2,5)
print(new_ticks)
plt.xticks(new_ticks)
plt.yticks([-2,-1.5,-1,0,1.2,3],[r'$worst$',r'$bad$',r'$\alpha$',r'$o$',r'$good$',r'$best$'])
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))
plt.show()
加圖例
plt.legend() 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3,3,50)
y1 = 2*x+1
y2 = x**2
plt.xlim((-1,2))
plt.ylim((-2,3))
plt.xlabel('x coordinate')
plt.ylabel('y coordinate')
new_ticks = np.linspace(-1,2,5)
plt.xticks(new_ticks)
plt.yticks([-2,-1.5,-1,0,1.2,3],[r'$worst$',r'$bad$',r'$\alpha$',r'$o$',r'$good$',r'$best$'])
plt.figure()
line1, = plt.plot(x,y2,label = 'up') # plt.plot() actually have a returns
line2, = plt.plot(x,y1,color = 'green',linewidth = 1,linestyle = '--',label = 'down')
plt.legend(handles = [line1,line2],labels = ['Quadratic function','linear function'],loc = 'best')
# if you just want to have one legend you can change the parameter of labels,for examples:labels = ['Quadratic function,'] ,remember to add a comma after the first label
plt.show() ###
圖像做局部的註釋(annotation)
plt.plot()是將整個函式圖形用線畫出來,若使用plt.scatter()則會將使用者提供的點繪出,不會自動將他話成一個直線,所以我們這邊使用plt.scatter()來做局部點的顯現,plt.scatter()的第一個參數放X座標,第二個放Y座標,第三個參數可以放尺寸,s
=
尺寸,第四個參數可以放顏色,然而plt.scatter()還有更多參數,這邊只先用這幾個。接著我們再為圖像增加更多輔助,我們加入plt.plot([x0,x0],[y0,0],'k--',lw
= 2.5)、plt.plot([0,x0],[y0,y0],'k--',lw = 2,color =
'purple')是為了輔助觀看,在圖中為點做延伸,第一個參數是放x座標的起點到終點,第二個參數是放y座標的起點和終點,第三個參數是放線條的樣式,第四個是放線條的尺寸。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3,3,50)
y = 2*x+1
plt.figure()
plt.plot(x,y,color = 'r')
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.spines['bottom'].set_position(('data',0))
ax.spines['left'].set_position(('data',0))
x0 = 1
y0 = 2*x0+1
plt.scatter(x0,y0,s = 50,color = 'b')
plt.plot([x0,x0],[y0,0],'k--',lw = 2)
plt.plot([0,x0],[y0,y0],'k--',lw = 2,color = 'purple')
plt.show()
接著進入註釋的部分,這裡會用到一個函式,plt.annotate(),先來看範例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3,3,50)
y = 2*x+1
plt.figure()
plt.plot(x,y,color = 'r')
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.spines['bottom'].set_position(('data',0))
ax.spines['left'].set_position(('data',0))
x0 = 1
y0 = 2*x0+1
plt.scatter(x0,y0,s = 50,color = 'b')
plt.plot([x0,x0],[y0,0],'k--',lw = 2)
plt.plot([0,x0],[y0,y0],'y--',lw = 2)
plt.annotate(r'2x+1 = %s' % y0,xy = (x0,y0),xycoords = 'data',xytext = (+30,-30),textcoords = 'offset points',fontsize = 20,arrowprops = dict(arrowstyle = '->',connectionstyle = 'arc3,rad = .2'))
plt.show()1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3,3,50)
y = 2*x+1
plt.figure()
plt.plot(x,y,color = 'r')
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.spines['bottom'].set_position(('data',0))
ax.spines['left'].set_position(('data',0))
x0 = 1
y0 = 2*x0+1
plt.scatter(x0,y0,s = 50,color = 'b')
plt.plot([x0,x0],[y0,0],'k--',lw = 2)
plt.plot([0,x0],[y0,y0],'y--',lw = 2)
plt.annotate('2x+1 = %s' % y0,xy = (x0,y0),xycoords = 'data',xytext = (+30,-30),textcoords = 'offset points',fontsize = 20,arrowprops = dict(arrowstyle = '->',connectionstyle = 'arc3,rad = .2'))
plt.text(-3,3,r'$I\ am\ a\ text$',color = "red",fontsize = 20)
plt.show() ###
單位ticks被擋住(ticks能見度)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3,3,50)
y = 2*x+1
plt.figure()
plt.plot(x,y,color = 'r',linewidth = 20,zorder = 1)
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))
for label in ax.get_xticklabels() + ax.get_yticklabels():
label.set_fontsize(12)
label.set_bbox(dict(facecolor = 'yellow',edgecolor = 'black',alpha = 0.7))
plt.show() ### scatter散點圖
今天如果要畫一個點狀散佈圖,可以使用scatter()函式,而我要的是隨機散佈圖,所以這邊使用random函式。
1
2
3
4
5
6
7
8
9
10
11
12
13import matplotlib.pyplot as plt
import numpy as np
data_size = 1024
x = np.random.normal(0,1,data_size)
y = np.random.normal(0,1,data_size)
dot_color = np.arctan2(x,y)
plt.scatter(x,y,s = 60,c = dot_color,alpha = 0.5)
plt.xlim((-2,2))
plt.ylim((-2,2))
plt.xticks(())
plt.yticks(())
plt.show()
而如果是要畫連續的點,則可以用arange()創造出連續的點。
1
2
3
4
5
6import matplotlib.pyplot as plt
import numpy as np
x = np.arange(10)
y = np.arange(10)
plt.scatter(x,y)
plt.show() ### 繪製長條圖
我們如果畫長條圖,可以使用plt.bar(),首先我們要有x座標和y座標,製造出xy座標後將座標加入bar裡,而bar裡的facecolor和edgecolor分別代表長條圖背景顏色和邊框顏色,最後再用一個迴圈將每一個值輸出即可。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17import matplotlib.pyplot as plt
import numpy as np
n = 12
x = np.arange(n)
y = (1-x/float(n))*np.random.uniform(0.5,1.0,n)
plt.bar(x,y,facecolor = '#9999ff',edgecolor = 'black')
for i,j in zip(x,y):
plt.text(i,j+0.01,'%.2f' % j,ha = 'center',va = 'bottom')
plt.xticks(())
plt.yticks(())
plt.ylim((0,1.1))
plt.show() ###
繪出等高線圖
在matplotlib有許多函式可以繪出等高線圖,例如contour()、contourf()、tricontour()、tricontourf(),contour()、contourf()在帶入參數的時候是要帶入一個網格,而tricontour()、tricontourf()在帶入的時候只需帶入xlist、ylist、zlist即可,但contour()、contourf()的效果比較好,所以這邊會使用contour()、contourf()來繪製。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20import matplotlib.pyplot as plt
import numpy as np
def height(x,y):
return (1-x/2+x**5+y**3)*np.exp(-x**2-y**2)
n = 512
x = np.linspace(-5, 5, n)
y = np.linspace(-5, 5, n)
x1, y1 = np.meshgrid(x,y)
plt.contourf(x1, y1, height(x1,y1),10,alpha = 0.75,cmap = plt.cm.cool)
c = plt.contour(x1,y1,height(x1,y1),10,colors = 'black',linewidth = 0.5)
plt.clabel(c,inline = True,fontsize = 10)
plt.xticks(())
plt.xlim((3,-3))
plt.ylim((3,-3))
plt.yticks(())
plt.show() ### 製作出顏色圖片
1
2
3
4
5
6
7
8
9
10import matplotlib.pyplot as plt
import numpy as np
a = np.array([0.33759320,0.63967205,0.40184628,0.64918592,0.49503721,0.44839065,0.35820281,0.53840583,0.38305164]).reshape(3,3)
plt.imshow(a,interpolation = 'spline36',cmap = 'bone',origin = 'upper')
plt.colorbar(shrink = 0.9)
plt.xticks(())
plt.yticks(())
plt.show()
首先我們要建造一個array裡面存放一些數據,這些數據是為了建造出深淺不一的顏色,接著用reshape()來更改它的維度,接著使用imshow()來顯示出圖片,我們在imshow()的第一個參數加入剛剛設定好的array,第二個參數輸入你想要的顯示方式,有許多種,可以參考這裡來查看其他種形式,第三個輸入你要的顏色形式,第四個加入你顏色的大小排序。
最後輸入plt.colorbar()可以顯示旁邊的顏色數值對照圖,加入的第一個參數是將對照圖的大小進行壓縮。
### 製作3D圖片
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = Axes3D(fig)
x = np.arange(-4,4,0.25)
y = np.arange(-4,4,0.25)
x,y = np.meshgrid(x,y)
tmp = np.sqrt(x**2+y**2)
z = np.sin(tmp)
ax.plot_surface(x,y,z,rstride = 1,cstride = 1,cmap = plt.get_cmap('rainbow'))
ax.contourf(x,y,z,zdir = 'z',offset = -2,cmap = 'rainbow')
ax.set_zlim(-2,2)
plt.show()