plot語句中支持除X,Y之外的參數,以字符串形式存在,來控制顏色、線型、點型等要素,語法形式爲:
plt.plot(X, Y, 'format', ...)python
顏色app
參數color或c 五種定義顏色值的方式 別名 color='r' 合法的HTML顏色名 color = 'red' HTML十六進制字符串 color = '#eeefff' 歸一化到[0, 1]的RGB元組 color = (0.3, 0.3, 0.4) 灰度 color = (0.1)
透明度dom
# 透明度 y = np.arange(1, 3) plt.plot(y, c="red", alpha=0.1); # 設置透明度 plt.plot(y+1, c="red", alpha=0.5); plt.plot(y+2, c="red", alpha=0.9);
背景色ide
設置背景色,經過plt.subplot()方法傳入facecolor參數,來設置座標軸的背景色函數
plt.subplot(facecolor='cyan'); plt.plot(np.random.randn(10),np.arange(1,11))
線型this
線型spa
線條風格 | 描述 | 線條風格 | 描述 |
---|---|---|---|
' - ' | 實線 | ' : ' | 虛線 |
' -- ' | 破折線 | 'steps' | 階梯線 |
' -. ' | 點劃線 | '' | 沒有 |
點型3d
y = np.arange(1, 3, 0.2) plt.plot(y, '1', y+0.5, '2', y+1, '3', y+1.5,'4'); plt.plot(y+2, '3') #不聲明marker,默認ls = None plt.plot(y+2.5,marker = '3') #聲明瞭marker,ls 默認是實線 plt.show()
多參數連用code
#顏色、點型、線型 x = np.linspace(0, 5, 10) plt.plot(x,3*x,'r-.') plt.plot(x, x**2, 'b^:') # blue line with dots plt.plot(x, x**3, 'go-.') # green dashed line plt.show()
點線的設置orm
參數 | 描述 | 參數 | 描述 |
---|---|---|---|
color或c | 線的顏色 | linestyle或ls | 線型 |
linewidth或lw | 線寬 | marker | 點型 |
markeredgecolor | 點邊緣的顏色 | markeredgewidth | 點邊緣寬度 |
makerfacecolor | 點內部的顏色 | markersize | 點大小 |
三種設置方式
對實例使用一系列的setter方法
x = np.arange(0,10) y = np.random.randint(10,30,size = 10) line,= plt.plot(x, y) line2 = plt.plot(x,y*2,x,y*3) line.set_linewidth(5) line2[1].set_marker('o') print(line,line2)
使用setp()方法
line = plt.plot(x, y) plt.setp(line, 'linewidth', 1.5,'color','r','marker','o','linestyle','--')
x = [5, 3, 7, 2, 4, 1] plt.plot(x); plt.xticks(range(len(x)), ['a', 'b', 'c', 'd', 'e', 'f']); # 傳入位置和標籤參數,以修改座標軸刻度 plt.yticks(range(1, 8, 2)); plt.show()
set_xticks、set_yticks、set_xticklabels、set_yticklabels方法 fig = plt.figure(figsize=(10, 4)) ax = fig.add_subplot(111) x = np.linspace(0, 5, 100) ax.plot(x, x**2, x, x**3, lw=2) ax.set_xticks([1, 2, 3, 4, 5]) ax.set_xticklabels(['a','b','c','d','e'], fontsize=18) yticks = [0, 50, 100, 150] ax.set_yticks(yticks) ax.set_yticklabels([y for y in yticks], fontsize=18); # use LaTeX formatted labels
x = np.arange(-np.pi,np.pi,0.01) plt.figure(figsize=(12,9)) plt.plot(x,np.sin(x),x,np.cos(x)) plt.axis([x.min()-1,x.max()+1,-1.2,1.2]) #xticks:參數一刻度,參數二,對應刻度上的值 plt.xticks(np.arange(-np.pi,np.pi+1,np.pi/2), ['$-\delta$','$-\pi$/2','0','$\pi$/2','$\pi$'],size = 20) plt.yticks([-1,0,1],['min','0','max'],size = 20) plt.show()
直方圖 【直方圖的參數只有一個x!!!不像條形圖須要傳入x,y】
hist()
的參數
bins
能夠是一個bin數量的整數值,也能夠是表示bin的一個序列。默認值爲10
normed
若是值爲True,直方圖的值將進行歸一化處理,造成機率密度,默認值爲False
color
指定直方圖的顏色。能夠是單一顏色值或顏色的序列。若是指定了多個數據集合,顏色序列將會設置爲相同的順序。若是未指定,將會使用一個默認的線條顏色
orientation
經過設置orientation
爲horizontal 橫向
建立水平直方圖。默認值爲vertical 縱向
x = np.random.randint(5,size = 5) display(x) plt.hist(x,histtype = 'bar');
正態分佈
u = 100 #數學指望 s = 15 #方差 x = np.random.normal(u,s,1000) # 生成正太分佈數據 ax = plt.gca() #獲取當前圖表 ax.set_xlabel('Value') ax.set_ylabel('Frequency') #設置x,y軸標題 ax.set_title("Histogram normal u = 100 s = 15") #設置圖表標題 ax.hist(x,bins = 100,color = 'r',orientation='horizontal') plt.show()
條形圖
bar() 方法 : 第一個參數爲條形左下角的x軸座標,第二個參數爲條形的高度;
matplotlib會自動設置條形的寬度,本例中條形寬0.8
plt.bar([1, 2, 3], [3, 2, 5]); plt.show()
# 例子:繪製並列條形圖 data1 = 10*np.random.rand(5) data2 = 10*np.random.rand(5) data3 = 10*np.random.rand(5) locs = np.arange(1, len(data1)+1) width = 0.27 plt.bar(locs, data1, width=width); plt.bar(locs+width, data2, width=width, color='red'); plt.bar(locs+2*width, data3, width=width, color='green') ; plt.xticks(locs + width*1, locs); plt.show()
barh方法
plt.barh([1, 2, 3], [3, 2, 5],height = 0.27,color = 'cyan'); plt.show()
餅狀圖
餅圖:【餅圖也只有一個參數x!】
pie()
餅圖適合展現各部分佔整體的比例,條形圖適合比較各部分的大小
常規的餅圖繪製
plt.figure(figsize = (4,4)) # 餅圖繪製正方形 x = [45,35,20] #百分比 labels = ['Cats','Dogs','Fishes'] #每一個區域名稱 plt.pie(x,labels = labels) plt.show()
部分餅圖的繪製
plt.figure(figsize=(4, 4)); x = [0.1, 0.2, 0.3] # 當各部分之和小於1時,則不計算各部分佔整體的比例,餅的大小是數值和1之比 labels = ['Cats', 'Dogs', 'Fishes'] plt.pie(x, labels=labels); # labels參數能夠設置各區域標籤 plt.show()
切分的餅圖
# labels參數設置每一塊的標籤;labeldistance參數設置標籤距離圓心的距離(比例值) # autopct參數設置比例值的顯示格式(%1.1f%%);pctdistance參數設置比例值文字距離圓心的距離 # explode參數設置每一塊頂點距圓形的長度(比例值);colors參數設置每一塊的顏色; # shadow參數爲布爾值,設置是否繪製陰影 plt.figure(figsize=(4, 4)); x = [4, 9, 21, 55, 30, 18] labels = ['Swiss', 'Austria', 'Spain', 'Italy', 'France', 'Benelux'] explode = [0.2, 0.1, 0, 0, 0.1, 0] colors = ['r', 'k', 'b', 'm', 'c', 'g'] plt.pie(x, labels=labels, labeldistance=1.2, explode=explode, colors=colors, autopct='%1.1f%%', pctdistance=0.5, shadow=True); plt.show()
散點圖
散點圖 : 【散點圖須要兩個參數x,y,但此時x不是表示x軸的刻度,而是每一個點的橫座標!】
scatter()
# s參數設置散點的大小;c參數設置散點的顏色;marker參數設置散點的形狀 x = np.random.randn(1000) y = np.random.randn(1000) size = 50*abs(np.random.randn(1000)) colors = np.random.randint(16777215,size = 1000) li = [] for color in colors: a = hex(color) str1 = a[2:] l = len(str1) for i in range(1,7-l): str1 = '0'+str1 str1 = "#" + str1 li.append(str1) plt.scatter(x, y,s = size, c=li, marker='d'); plt.show()
複雜的餅圖的繪製
import numpy as np import pandas as pd from pandas import Series,DataFrame import matplotlib.pyplot as plt x = np.random.randn(1000) y1 = np.random.randn(1000) y2 = 1.2 + np.exp(x) #exp(x) 返回的是e的x次方 ax1 = plt.subplot(121) plt.scatter(x,y1,color = 'purple',alpha = 0.3,edgecolors = 'white',label = 'no correl') plt.xlabel('no correlation') plt.grid(True) plt.legend() ax2 = plt.subplot(122) plt.scatter(x,y2,color = 'green',alpha = 0.3,edgecolors = 'gray',label = 'correl') plt.xlabel('correlation') plt.grid(True) plt.legend() plt.show()
圖形的文字,註釋,箭頭
pyplot函數 | API方法 | 描述 |
---|---|---|
text() | mpl.axes.Axes.text() | 在Axes對象中任意位置添加文字 |
xlabel | mpl.axes.Axes.set_xlabel() | 爲X軸添加標籤 |
ylabel | mpl.axes.Axes.set_ylabel() | 爲y軸添加標籤 |
title() | mpl.axes.Axes.set_title() | 爲Axes對象添加標題 |
legend() | mpl.axes.Axes.legend() | 爲Axes對象添加圖例 |
figtext() | mpl.figure.Figure.text() | 在Figure對象中任意位置添加文字 |
suptitle() | mpl.figure.Figure.suptitle() | 在Figure對象中添加中心化標題 |
annnotate | mpl.axes.Axes.annnotate() | 在Axes對象添加註釋(箭頭) |
註釋
# xy參數設置箭頭指示的位置,xytext參數設置註釋文字的位置 # arrowprops參數以字典的形式設置箭頭的樣式 # width參數設置箭頭長方形部分的寬度,headlength參數設置箭頭尖端的長度, # headwidth參數設置箭頭尖端底部的寬度,shrink參數設置箭頭頂點、尾部與指示點、註釋文字的距離(比例值) y = [13, 11, 13, 12, 13, 10, 30, 12, 11, 13, 12, 12, 12, 11, 12] plt.plot(y); plt.ylim(ymax=35); # 爲了讓註釋不會超出圖的範圍,須要調整y座標軸的界限 plt.annotate('this spot must really\nmean something', xy=(6, 30), xytext=(8, 31.5), arrowprops=dict(width=15, headlength=20, headwidth=20, facecolor='black', shrink=0.1)); plt.show()
# 生成3個正態分佈數據數據集 x1 = np.random.normal(30, 3, 100) x2 = np.random.normal(20, 2, 100) x3 = np.random.normal(10, 3, 100) # 繪製3個數據集,併爲每一個plot指定一個字符串標籤 plt.plot(x1, label='plot') # 若是不想在圖例中顯示標籤,能夠將標籤設置爲_nolegend_ plt.plot(x2, label='2nd plot') plt.plot(x3, label='last plot') # 繪製圖例 plt.legend(bbox_to_anchor=(0, 1.02, 1, 0.102), # 指定邊界框起始位置爲(0, 1.02),並設置寬度爲1,高度爲0.102 ncol=3, # 設置列數爲3,默認值爲1 mode="expand", # mode爲None或者expand,當爲expand時,圖例框會擴展至整個座標軸區域 borderaxespad=0.) # 指定座標軸和圖例邊界之間的間距 # 繪製註解 plt.annotate("Important value", # 註解文本的內容 xy=(55,20), # 箭頭終點所在位置 xytext=(5, 38), # 註解文本的起始位置,箭頭由xytext指向xy座標位置 arrowprops=dict(arrowstyle='->')); # arrowprops字典定義箭頭屬性,此處用arrowstyle
箭頭
plt.figure(figsize=(12,9)) plt.axis([0, 10, 0, 20]); arrstyles = ['-', '->', '-[', '<-', '<->', 'fancy', 'simple', 'wedge'] for i, style in enumerate(arrstyles): plt.annotate(style, xytext=(1, 2+2*i), xy=(4, 1+2*i), arrowprops=dict(arrowstyle=style)); connstyles=["arc", "arc,angleA=10,armA=30,rad=30", "arc3,rad=.2", "arc3,rad=-.2", "angle", "angle3"] for i, style in enumerate(connstyles): plt.annotate(style, xytext=(6, 2+2*i), xy=(8, 1+2*i), arrowprops=dict(arrowstyle='->', connectionstyle=style)); plt.show()
3D圖形繪製
import numpy as np import matplotlib.pyplot as plt #3d圖形必須的 from mpl_toolkits.mplot3d.axes3d import Axes3D %matplotlib inline #係數,由X,Y生成Z a = 0.7 b = np.pi #計算Z軸的值 def mk_Z(X, Y): return 2 + a - 2 * np.cos(X) * np.cos(Y) - a * np.cos(b - 2*X) #生成X,Y,Z x = np.linspace(0, 2*np.pi, 100) y = np.linspace(0, 2*np.pi, 100) X,Y = np.meshgrid(x, y) Z = mk_Z(X, Y) fig = plt.figure(figsize=(14,6)) #建立3d的視圖,使用屬性projection ax = fig.add_subplot(1, 2, 1, projection='3d') ax.plot_surface(X,Y,Z,rstride = 5,cstride = 5) #建立3d視圖,使用colorbar,添加顏色柱 ax = fig.add_subplot(1, 2, 2, projection='3d') p = ax.plot_surface(X, Y, Z, rstride=5, cstride=5, cmap='rainbow', antialiased=True) cb = fig.colorbar(p, shrink=0.5)
玫瑰圖繪製
極座標條形圖
#極座標條形圖 def showRose(values,title): max_value = values.max() # 分爲8個面元 N = 8 # 面元的分隔角度 angle = np.arange(0.,2 * np.pi, 2 * np.pi / N) # 每一個面元的大小(半徑) radius = np.array(values) # 設置極座標條形圖 plt.axes([0, 0, 2, 2], polar=True,facecolor = 'g') colors = [(1 - x/max_value, 1 - x/max_value, 0.75) for x in radius] # 畫圖 plt.bar(angle, radius, width=(2*np.pi/N), bottom=0.0, color=colors) plt.title(title,x=0.2, fontsize=20) #拉韋納(Ravenna)又譯「臘萬納」「拉文納」「拉溫拿」。意大利北部城市。位於距亞得里亞海10千米的沿海平原上 data = np.load('Ravenna_wind.npy') hist, angle = np.histogram(data,8,[0,360]) showRose(hist,'Ravenna')