Python Matplotlib基本用法
Python Matplotlib基本用法
- 1. 認(rèn)識(shí)Matploblib
- 1.1 Figure
- 1.2 Axes
- 1.3 Multiple Axes
- 1.4 Axes Vs .pyplot
- 2. 基本繪圖2D
- 2.1 線
- 2.2 散點(diǎn)圖
- 2.3 條形圖
- 2.4 直方圖
- 2.5 餅圖
- 2.6 箱形圖
- 2.7 泡泡圖
- 2.8 等高線(輪廓圖)
- 3 布局、圖例說明、邊界等
- 3.1區(qū)間上下限
- 3.2 圖例說明
- 3.3 區(qū)間分段
- 3.4 布局
- 3.5 軸相關(guān)
Matplotlib 是Python中類似 MATLAB 的繪圖工具,熟悉 MATLAB 也可以很快的上手 Matplotlib。
1. 認(rèn)識(shí)Matploblib
1.1 Figure
在任何繪圖之前,我們需要一個(gè)Figure對(duì)象,可以理解成我們需要一張畫板才能開始繪圖。
import matplotlib.pyplot as pltfig = plt.figure()1.2 Axes
在擁有Figure對(duì)象之后,在作畫前我們還需要軸,沒有軸的話就沒有繪圖基準(zhǔn),所以需要添加Axes。也可以理解成為真正可以作畫的紙。
import matplotlib.pyplot as pltfig = plt.figure() ax = fig.add_subplot(111) ax.set(xlim=[0.5, 4.5], ylim=[-2, 8], title='An Example Axes',xlabel='X-Axis', ylabel='Y-Axis') plt.show()以上的代碼,在一幅圖上添加了一個(gè)Axes,然后設(shè)置了這個(gè)Axes的X軸以及Y軸的取值范圍(這些設(shè)置并不是強(qiáng)制的,后面會(huì)再談到關(guān)于這些設(shè)置),效果如下圖:
對(duì)于上面的fig.add_subplot(111)就是添加Axes的,參數(shù)的解釋的在畫板的第1行第1列的第一個(gè)位置生成一個(gè)Axes對(duì)象來準(zhǔn)備作畫。也可以通過fig.add_subplot(2, 2, 1)的方式生成Axes,前面兩個(gè)參數(shù)確定了面板的劃分,例如 2, 2會(huì)將整個(gè)面板劃分成 2 * 2 的方格,第三個(gè)參數(shù)取值范圍是[1, 2*2]表示第幾個(gè)Axes。如下面的例子:
1.3 Multiple Axes
可以發(fā)現(xiàn)我們上面添加 Axes 似乎有點(diǎn)弱雞,所以提供了下面的方式一次性生成所有 Axes:
import matplotlib.pyplot as pltfig, axes = plt.subplots(nrows=2, ncols=2) axes[0, 0].set(title='Upper Left') axes[0, 1].set(title='Upper Right') axes[1, 0].set(title='Lower Left') axes[1, 1].set(title='Lower Right') plt.show()
fig 還是我們熟悉的畫板, axes 成了我們常用二維數(shù)組的形式訪問,這在循環(huán)繪圖時(shí),額外好用。
1.4 Axes Vs .pyplot
相信不少人看過下面的代碼,很簡(jiǎn)單并易懂,但是下面的作畫方式只適合簡(jiǎn)單的繪圖,快速的將圖繪出。在處理復(fù)雜的繪圖工作時(shí),我們還是需要使用Axes來完成作畫的。
import matplotlib.pyplot as pltplt.plot([1, 2, 3, 4], [2, 4, 8, 16], color='lightblue', linewidth=3) plt.xlim(0.5, 4.5) plt.show()2. 基本繪圖2D
2.1 線
plot()函數(shù)畫出一系列的點(diǎn),并且用線將它們連接起來。看下例子:
import matplotlib.pyplot as plt import numpy as npx = np.linspace(0, np.pi * 6) y_sin = np.sin(x) y_cos = np.cos(x)fig = plt.figure() ax1 = fig.add_subplot(221) ax2 = fig.add_subplot(222) ax3 = fig.add_subplot(223) ax4 = fig.add_subplot(224) ax1.plot(x, y_sin) ax2.plot(x, y_sin, 'go--', linewidth=2, markersize=12) ax3.plot(x, y_cos) ax4.plot(x, y_cos, color='red', marker='+', linestyle='dashed') fig.show()在上面的三個(gè)Axes上作畫。plot,前面兩個(gè)參數(shù)為x軸、y軸數(shù)據(jù)。ax2的第三個(gè)參數(shù)是 MATLAB風(fēng)格的繪圖,對(duì)應(yīng)ax3上的顏色,marker,線型。
另外,我們可以通過關(guān)鍵字參數(shù)的方式繪圖,如下例:
發(fā)現(xiàn)上面的作圖,在數(shù)據(jù)部分只傳入了字符串,這些字符串對(duì)一個(gè)這 data_obj 中的關(guān)鍵字,當(dāng)以這種方式作畫時(shí),將會(huì)在傳入給 data 中尋找對(duì)應(yīng)關(guān)鍵字的數(shù)據(jù)來繪圖。
2.2 散點(diǎn)圖
只畫點(diǎn),但是不用線連接起來。
import matplotlib.pyplot as plt import numpy as npx = np.arange(10) y = np.random.randn(10) plt.scatter(x, y, color='red', marker='+') plt.show()2.3 條形圖
條形圖分兩種,一種是水平的,一種是垂直的,見下例子:
import matplotlib.pyplot as plt import numpy as npnp.random.seed(1) x = np.arange(5) y = np.random.randn(5)fig, axes = plt.subplots(ncols=2, figsize=plt.figaspect(1. / 2))vert_bars = axes[0].bar(x, y, color='lightblue', align='center') horiz_bars = axes[1].barh(x, y, color='lightblue', align='center') # 在水平或者垂直方向上畫線 axes[0].axhline(0, color='gray', linewidth=2) axes[1].axvline(0, color='gray', linewidth=2) plt.show()
條形圖還返回了一個(gè)Artists 數(shù)組,對(duì)應(yīng)著每個(gè)條形,例如上圖 Artists 數(shù)組的大小為5,我們可以通過這些 Artists 對(duì)條形圖的樣式進(jìn)行更改,如下例:
2.4 直方圖
直方圖用于統(tǒng)計(jì)數(shù)據(jù)出現(xiàn)的次數(shù)或者頻率,有多種參數(shù)可以調(diào)整,見下例:
import matplotlib.pyplot as plt import numpy as npnp.random.seed(19680801)n_bins = 10 x = np.random.randn(1000, 3)fig, axes = plt.subplots(nrows=2, ncols=2) ax0, ax1, ax2, ax3 = axes.flatten()colors = ['red', 'tan', 'lime'] ax0.hist(x, n_bins, density=True, histtype='bar', color=colors, label=colors) ax0.legend(prop={'size': 10}) ax0.set_title('bars with legend')ax1.hist(x, n_bins, density=True, histtype='barstacked') ax1.set_title('stacked bar')ax2.hist(x, histtype='barstacked', rwidth=0.5) ax2.set_title('stacked bar')ax3.hist(x[:, 0], rwidth=0.9) ax3.set_title('different sample sizes')fig.tight_layout() plt.show()參數(shù)中density控制Y軸是概率還是數(shù)量,與返回的第一個(gè)的變量對(duì)應(yīng)。histtype控制著直方圖的樣式,默認(rèn)是 ‘bar’,對(duì)于多個(gè)條形時(shí)就相鄰的方式呈現(xiàn)如子圖1, ‘barstacked’ 就是疊在一起,如子圖2、3。 rwidth 控制著寬度,這樣可以空出一些間隙,比較圖2、3. 圖4是只有一條數(shù)據(jù)時(shí)。
2.5 餅圖
import matplotlib.pyplot as plt import numpy as npnp.random.seed(19680801)labels = ['Frogs', 'Hogs', 'Dogs', 'Logs'] sizes = [15, 30, 45, 10] explode = (0, 0.1, 0, 0)fig1, (ax1, ax2) = plt.subplots(2) ax1.pie(sizes, labels=labels, autopct='%1.1f%%', shadow=True) ax1.axis('equal')ax2.pie(sizes, autopct='%1.2f%%', shadow=True, startangle=90,explode=explode, pctdistance=1.12) ax2.axis('equal') ax2.legend(labels=labels,loc='upper right') plt.show()餅圖自動(dòng)根據(jù)數(shù)據(jù)的百分比畫餅。labels是各個(gè)塊的標(biāo)簽,如子圖一。autopct=%1.1f%%表示格式化百分比精確輸出,explode,突出某些塊,不同的值突出的效果不一樣。pctdistance=1.12百分比距離圓心的距離,默認(rèn)是0.6
2.6 箱形圖
為了專注于如何畫圖,省去數(shù)據(jù)的處理部分。 data 的 shape 為 (n, ), data2 的 shape 為 (n, 3)。
import matplotlib.pyplot as plt import numpy as npdata1 = np.random.rand(10) data2 = np.random.rand(10, 3)fig1, (ax1, ax2) = plt.subplots(2) ax1.boxplot(data1) ax2.boxplot(data2, vert=False) # 控制方向plt.show() print(data1) print(data2)2.7 泡泡圖
散點(diǎn)圖的一種,加入了第三個(gè)值 s 可以理解成普通散點(diǎn),畫的是二維,泡泡圖體現(xiàn)了Z的大小,如下例:
import matplotlib.pyplot as plt import numpy as npnp.random.seed(19680801) N = 50 x = np.random.rand(N) y = np.random.rand(N) colors = np.random.rand(N) area = (30 * np.random.rand(N)) ** 2plt.scatter(x, y, s=area, c=colors, alpha=0.5) plt.show()2.8 等高線(輪廓圖)
有時(shí)候需要描繪邊界的時(shí)候,就會(huì)用到輪廓圖,機(jī)器學(xué)習(xí)用的決策邊界也常用輪廓圖來繪畫,見下例:
import matplotlib.pyplot as plt import numpy as npnp.random.seed(19680801) fig, (ax1, ax2) = plt.subplots(2) x = np.arange(-5, 5, 0.1) y = np.arange(-5, 5, 0.1) xx, yy = np.meshgrid(x, y, sparse=True) z = np.sin(xx ** 2 + yy ** 2) / (xx ** 2 + yy ** 2) ax1.contourf(x, y, z) ax2.contour(x, y, z) plt.show()上面畫了兩個(gè)一樣的輪廓圖,contourf會(huì)填充輪廓線之間的顏色。數(shù)據(jù)x, y, z通常是具有相同shape的二維矩陣。x, y可以為一維向量,但是必需有z.shape = (y.n, x.n),這里y.n和x.n分別表示x、y的長度。Z通常表示的是距離X-Y平面的距離,傳入X、Y則是控制了繪制等高線的范圍。
3 布局、圖例說明、邊界等
3.1區(qū)間上下限
當(dāng)繪畫完成后,會(huì)發(fā)現(xiàn)X、Y軸的區(qū)間是會(huì)自動(dòng)調(diào)整的,并不是跟我們傳入的X、Y軸數(shù)據(jù)中的最值相同。為了調(diào)整區(qū)間我們使用下面的方式:
ax.set_xlim([xmin, xmax]) #設(shè)置X軸的區(qū)間 ax.set_ylim([ymin, ymax]) #Y軸區(qū)間 ax.axis([xmin, xmax, ymin, ymax]) #X、Y軸區(qū)間 ax.set_ylim(bottom=-10) #Y軸下限 ax.set_xlim(right=25) #X軸上限具體效果見下例:
import matplotlib.pyplot as plt import numpy as npnp.random.seed(19680801) x = np.linspace(0, 2 * np.pi) y = np.sin(x)fig, (ax1, ax2) = plt.subplots(2) ax1.plot(x, y) ax2.plot(x, y) ax2.set_xlim([-1, 6]) ax2.set_ylim([-1, 3]) plt.show()3.2 圖例說明
我們?nèi)绻覀冊(cè)谝粋€(gè)Axes上做多次繪畫,那么可能出現(xiàn)分不清哪條線或點(diǎn)所代表的意思。這個(gè)時(shí)間添加圖例說明,就可以解決這個(gè)問題了,見下例:
import matplotlib.pyplot as plt import numpy as npnp.random.seed(19680801) fig, ax = plt.subplots() ax.plot([1, 2, 3, 4], [10, 20, 25, 30], label='Philadelphia') ax.plot([1, 2, 3, 4], [30, 23, 13, 4], label='Boston') ax.scatter([1, 2, 3, 4], [20, 10, 30, 15], label='Point') ax.set(ylabel='Temperature (deg C)', xlabel='Time', title='A tale of two cities') ax.legend() plt.show()3.3 區(qū)間分段
默認(rèn)情況下,繪圖結(jié)束之后,Axes 會(huì)自動(dòng)的控制區(qū)間的分段。見下例:
import matplotlib.pyplot as plt import numpy as npnp.random.seed(19680801) data = [('apples', 2), ('oranges', 3), ('peaches', 1)] fruit, value = zip(*data) fig, (ax1, ax2) = plt.subplots(2) x = np.arange(len(fruit)) ax1.bar(x, value, align='center', color='gray') ax2.bar(x, value, align='center', color='gray') ax2.set(xticks=x, xticklabels=fruit) plt.show()上面不僅修改了X軸的區(qū)間段,并且修改了顯示的信息為文本。
3.4 布局
當(dāng)我們繪畫多個(gè)子圖時(shí),就會(huì)有一些美觀的問題存在,例如子圖之間的間隔,子圖與畫板的外邊間距以及子圖的內(nèi)邊距,下面說明這個(gè)問題:
fig, axes = plt.subplots(2, 2, figsize=(9, 9)) fig.subplots_adjust(wspace=0.5, hspace=0.3,left=0.125, right=0.9,top=0.9, bottom=0.1)#fig.tight_layout() #自動(dòng)調(diào)整布局,使標(biāo)題之間不重疊 plt.show()通過fig.subplots_adjust()我們修改了子圖水平之間的間隔wspace=0.5,垂直方向上的間距hspace=0.3,左邊距l(xiāng)eft=0.125等等,這里數(shù)值都是百分比的。以[0, 1]為區(qū)間,選擇left、right、bottom、top注意top 和 right是 0.9 表示上、右邊距為百分之10。不確定如果調(diào)整的時(shí)候,fig.tight_layout()是一個(gè)很好的選擇。之前說到了內(nèi)邊距,內(nèi)邊距是子圖的,也就是Axes對(duì)象,所以這樣使用ax.margins(x=0.1, y=0.1),當(dāng)值傳入一個(gè)值時(shí),表示同時(shí)修改水平和垂直方向的內(nèi)邊距。
觀察上面的四個(gè)子圖,可以發(fā)現(xiàn)他們的X、Y的區(qū)間是一致的,而且這樣顯示并不美觀,所以可以調(diào)整使他們使用一樣的X、Y軸:
import matplotlib.pyplot as plt import numpy as npfig, (ax1, ax2) = plt.subplots(1, 2, sharex=True, sharey=True) ax1.plot([1, 2, 3, 4], [1, 2, 3, 4]) ax2.plot([3, 4, 5, 6], [6, 5, 4, 3]) plt.show()3.5 軸相關(guān)
改變邊界的位置,去掉四周的邊框:
fig, ax = plt.subplots() ax.plot([-2, 2, 3, 4], [-10, 20, 25, 5]) ax.spines['top'].set_visible(False) #頂邊界不可見 ax.xaxis.set_ticks_position('bottom') # ticks 的位置為下方,分上下的。 ax.spines['right'].set_visible(False) #右邊界不可見 ax.yaxis.set_ticks_position('left') # "outward" # 移動(dòng)左、下邊界離 Axes 10 個(gè)距離 #ax.spines['bottom'].set_position(('outward', 10)) #ax.spines['left'].set_position(('outward', 10))# "data" # 移動(dòng)左、下邊界到 (0, 0) 處相交 ax.spines['bottom'].set_position(('data', 0)) ax.spines['left'].set_position(('data', 0))# "axes" # 移動(dòng)邊界,按 Axes 的百分比位置 #ax.spines['bottom'].set_position(('axes', 0.75)) #ax.spines['left'].set_position(('axes', 0.3))plt.show() 與50位技術(shù)專家面對(duì)面20年技術(shù)見證,附贈(zèng)技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的Python Matplotlib基本用法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 深度学习入门之线性模型和梯度下降
- 下一篇: 深度神经网络实践:车牌识别