python Matplotlib數(shù)據(jù)可視化(2):詳解三大容器對象與常用設(shè)置
上一篇博客中說到,matplotlib中所有畫圖元素(artist)分為兩類:基本型和容器型。容器型元素包括三種:figure、axes、axis。一次畫圖的必經(jīng)流程就是先創(chuàng)建好figure實例,接著由figure去創(chuàng)建一個或者多個axes,然后通過axes實例調(diào)用各種方法來添加各種基本型元素,最后通過axes實例本身的各種方法亦或者通過axes獲取axis實例實現(xiàn)對各種元素的細節(jié)操控。
本篇博客繼續(xù)上一節(jié)的內(nèi)容,展開介紹三大容器元素創(chuàng)建即通過三大容器可以完成的常用設(shè)置。
1 figure
1.1 創(chuàng)建figure
在上文中我們一直提到的figure指的是Figure類的實例化對象,當然我們一般不會直接去實例化Figure類,因為這樣創(chuàng)建的Figure實例對象不能納入序列中共同管理。matplotlib中提供了多種方法創(chuàng)建figure,其中屬pyplot模塊中的figure()方法最常用也最方便,下面我們來說說這個方法。
figure方法參數(shù)如下:
- num:整型或字符串類型,可選參數(shù),默認為None。這個參數(shù)課可以理解為是figure的身份標識,即id。當值為None時,會創(chuàng)建一個figure實例,該實例的num值會在已有基礎(chǔ)上自增;當該參數(shù)不為None時,如果與已有的num值重復(fù),則會切換到該figure使其處于激活狀態(tài),并返回一個該figure的引用;如果傳入的參數(shù)為字符串,該字符串將會被設(shè)置為figure的標題。
- figsize:tuple類型,可選參數(shù),默認為None。通過figsize參數(shù)可以設(shè)置figure的size,即(width, height),單位為inch。當值為None時,采用默認size。
- dpi:整型,可選參數(shù),用于設(shè)置圖片像素。
- facecolor:可選參數(shù),用于設(shè)置前景色,默認為白色。
- edgecolor:可選參數(shù),用于設(shè)置邊框顏色,默認為黑色。
- frameon:bool類型,可選參數(shù),表示是否繪制窗口的圖框,默認是。
- FigureClass:傳入一個類名,當使用自定義的類實例化figure時使用,默認為matplotlib.figure.Figure。
- clear:bool類型,可選參數(shù),默認為False。如果值為True的話,如果figure已存在,則會清除該figure的全部內(nèi)容。
from matplotlib import pyplot as plt import matplotlib as mpl import numpy as np mpl.rcParams['font.sans-serif'] = ['SimHei'] # 中文字體支持
fig = plt.figure(figsize=(4,2), facecolor='grey') # 創(chuàng)建figure fig.add_axes((0,0,1,1)) # 必須添加axes后才能顯示 plt.show()
在jupyter編輯器中,空白的figure是不會顯示的,所以必須在figure中至少添加一個axes。
1.2 figure的常用設(shè)置
1.2.1 set方法通用設(shè)置
創(chuàng)建figure時的各個參數(shù)基本都可以通過figure實例對象中對應(yīng)的對應(yīng)的set方法進行修改,例如set_facecolor()用來設(shè)置前景色,set_size_inches()用來設(shè)置大小等。
設(shè)置前景色:
fig = plt.figure(figsize=(4,2)) fig.set_facecolor('grey') # 設(shè)置前景色 plt.plot() plt.show()
fig = plt.figure() fig.set_size_inches(2,3) # 設(shè)置大小 plt.plot() plt.show()
1.2.2 設(shè)置figure標題
fig = plt.figure(figsize=(4,2)) fig.suptitle("figure title", color='red') # 設(shè)置figure標題 plt.plot() plt.show()
1.2.3 添加文本
fig = plt.figure(figsize=(4,2)) fig.text(0.5,0.5,"figure text",color='red') # 設(shè)置figure標題,前兩個參數(shù)分別表示到左邊框和上邊框的百分比距離 plt.plot() plt.show()
1.2.4 設(shè)置圖例
fig = plt.figure(figsize=(5,3)) axes = fig.add_axes((0,0,0.8,1)) x = np.linspace(0, 10, 1000) line1, = axes.plot(x, np.sin(x)) # 注意,line1后面有個逗號,因為plot()方法返回值是一個列表 line2, = axes.plot(x, np.cos(x)) fig.legend([line1, line2],['sin', 'cos']) plt.show()
1.2.5 設(shè)置子圖間距
fig, axes = plt.subplots(2,2,facecolor='grey') fig.subplots_adjust(left=None, # 設(shè)置畫圖區(qū)域與figure上下左右邊框的比例距離 bottom=None, right=None, top=None, wspace=0.3, # 子圖間水平方向距離 hspace=1) # 子圖間垂直方向距離 plt.show()
2 axes
axes可以認為是figure這張畫圖上的子圖,因為子圖上一般都是坐標圖,所以我更愿意理解為軸域或者坐標系。
2.1 創(chuàng)建axes
一個figure可以有多個axes, 無論是pyplot模塊還是figure實例內(nèi)都定義有多種創(chuàng)建axes的方法。 (1) plt.axes()
plt.axes()是指pyplot模塊中的axes()方法,該方法會在當前激活的figure中創(chuàng)建一個axes,并使創(chuàng)建好的axes處于激活狀態(tài)。當傳入的第一個位置參數(shù)為空時,該方法會創(chuàng)建一個占滿整個figure的axes;通常我們可以傳入一個tuple參數(shù)(left, botton, width, height)作為第一個位置參數(shù),tuple中四個元素分別表示與figure左邊框比例距離,邊框?qū)挾日糵igure寬度的比例,寬度比例,高度占figure高度的比例。通過這種方式添加axes時,matplotlib會自動創(chuàng)建一個axes,然后將創(chuàng)建好的axes按照給定的位置和size添加到figure中,最后返回一個axes的引用。
fig1 = plt.figure(figsize=(4,2), facecolor='grey') ax1 = plt.axes((0.1, 0.1, 0.8, 0.7), facecolor='green') fig2 = plt.figure(figsize=(4,2), facecolor='yellow') ax2 = plt.axes((0.1, 0.1, 0.8, 0.8), facecolor='red') # 這個axes將會被覆蓋在下面 plt.show()
注意,如果在相同區(qū)域添加axes,后面添加的axes會把前面添加的axes覆蓋。
fig = plt.figure(figsize=(4,2), facecolor='grey') ax1 = plt.axes((0.1, 0.1, 0.8, 0.8), facecolor='green') ax2 = plt.axes((0.1, 0.1, 0.8, 0.7), facecolor='red') # 這個axes將會被覆蓋在下面 plt.show()
(2) figure.add_axes()
figure.add_axes()方法的作用是將一個axes添加到figure中,這一方法可以傳入一個已創(chuàng)建好的axes作為第一個參數(shù),add_axes會將傳入的axes添加到figure中,但這種情況使用不多。在大多數(shù)情況下,我們會如同上述在plt.axes()方法中那樣傳遞一個tuple參數(shù)(left, botton, width, height)作為第一個位置參數(shù)。同樣,如果在相同區(qū)域添加axes,后面添加的axes會把前面添加的axes覆蓋。
fig = plt.figure(figsize=(4,2), facecolor='grey') fig.add_axes((0.1, 0.1, 0.3, 0.7), facecolor='green') # 這個axes將會被覆蓋在下面 fig.add_axes((0.5, 0.1, 0.3, 0.7), facecolor='red') plt.show()
(3) plt.subplot與plt.subplots()
plt.subplot和plt.subplots()是在pyplot模塊中定義的兩個方法,兩個方法都是將figure劃分為多行多列的網(wǎng)格,然后添加axes,但功能和用法卻有些許不同。
- plt.subplot()
plt.subplot主要包括三個參數(shù)(nrows, ncols, index),分別表示行數(shù)、列數(shù)和索引,該方法會根據(jù)指定的行列數(shù)對figure劃分為網(wǎng)格,讓后在指定索引的網(wǎng)格中創(chuàng)建axes,并返回該axes的引用。索引是從1開始從左往右,從上到下遞增,例如plt.subplot(2,2,4)表示將figure劃分為兩行兩列的4個網(wǎng)格,并在第4個子網(wǎng)格中創(chuàng)建一個axes然后返回。注意,每一次調(diào)用plt.subplot()方法只會在指定索引的子網(wǎng)格中創(chuàng)建axes,而不是在所有子網(wǎng)格中都創(chuàng)建axes,如果需要在多個子網(wǎng)格中創(chuàng)建axes,那么就需要多次調(diào)用plt.subplot()指定不同的索引。另外,如果nrows, ncols, index三個參數(shù)都小于10,可以將這三個參數(shù)合并成一個3位整數(shù)來寫,例如plt.subplot(2,2,4)與plt.subplot(224)是完全等效的。
fig = plt.figure(figsize=(4,4), facecolor='grey') ax1 = plt.subplot(221,facecolor='green') ax2 = plt.subplot(224,facecolor='red') plt.show()
- plt.subplots()
與plt.subplot()不同的是,plt.subplots()會重新創(chuàng)建一個figure,然后將創(chuàng)建好的figure按照指定的行列數(shù)劃分為網(wǎng)格,并在每一個子網(wǎng)格中各創(chuàng)建一個axes,最終同時返回figure和所有子網(wǎng)格中axes組成的numpy數(shù)組中。
fig, axes = plt.subplots(2,2,facecolor='grey') fig.suptitle('figure title') print(type(axes)) axes[0,0].set_facecolor('green') axes[1,1].set_facecolor('red') plt.show()
plt.subplots()還有一對參數(shù)sharex, sharey用于設(shè)置是否共享x軸或y軸,這對參數(shù)有取值可以使bool型或'none', 'all', 'row', 'col'這4個字符串中的一個,分別有以下含義:
- False 和 'none'表示不共享,任何子圖中的x軸或y軸都是相互獨立的;
- True 和 'all'表示所有子圖共享x軸或y軸;
- 'row' 表示同一行的子圖共享x軸或y軸;
- 'col' 表示同一列的子圖共享x軸或y軸;
fig, axes = plt.subplots(2,2,sharex=True,sharey=True,facecolor='grey') fig.suptitle('figure title') axes[0,0].set_facecolor('green') axes[1,1].set_facecolor('red') plt.show()
(4) figure.add_subplot()與figure.subplots()
figure.add_subplot與上文中介紹過的plt.subplot()無論是功能還是使用方法上都是幾乎一樣的,唯一區(qū)別就是plt.subplot()的目標是在當前激活的figure,而figure.add_subplot()是調(diào)用add_subplot()方法的figure。
fig = plt.figure(figsize=(4,4), facecolor='grey') ax1 = fig.add_subplot(221,facecolor='green') ax2 = fig.add_subplot(224,facecolor='red') plt.show()
figure.subplots()的功能、用法又與上文中介紹過的plt.subplots()很相似,區(qū)別在于figure.subplots()不會重新創(chuàng)建一個figure,而是對當前的figure進行劃分網(wǎng)格并在每一個網(wǎng)格中都創(chuàng)建一個axes。
fig = plt.figure(facecolor='grey') axes = fig.subplots(2,2) axes[0, 0].set_facecolor('green') axes[1, 1].set_facecolor('red') plt.show()
2.2 axes的常用設(shè)置
axes是matplotlib作圖中眾多元素的核心,可以說,大多數(shù)的設(shè)置都可以通過axes來完成。
2.2.1 設(shè)置標題
fig = plt.figure(facecolor='grey') fig.suptitle("figure 標題", color='red') ax1 = fig.add_subplot(121) ax2 = fig.add_subplot(122) ax1.set_title(' 圖 1') # 設(shè)置標題 ax2.set_title(' 圖 2') plt.show()
2.2.2 設(shè)置圖例
fig = plt.figure(figsize=(5,3)) axes = fig.add_axes((0,0,0.8,1)) x = np.linspace(0, 10, 1000) line1, = axes.plot(x, np.sin(x)) line2, = axes.plot(x, np.cos(x)) axes.legend([line1, line2],['正弦', '余弦']) plt.show()
2.2.3 設(shè)置坐標軸名稱
fig = plt.figure(figsize=(4,1)) axes = fig.add_axes((0,0,1,1)) axes.set_xlabel('x軸', fontsize=15) axes.set_ylabel('y軸', fontsize=15, color='red') plt.show()
2.2.4 設(shè)置坐標軸范圍
fig = plt.figure(figsize=(6,2)) axes = fig.add_axes((0,0,0.8,1)) x = np.linspace(-3, 5, 1000) line1, = axes.plot(x, np.sin(x)) axes.set_xlim((-3,5)) # 設(shè)置橫坐標范圍 axes.set_ylim((-3,3)) # 設(shè)置縱坐標范圍 plt.show()
2.2.5 隱藏邊框
fig = plt.figure(figsize=(6,2)) axes = fig.add_axes((0,0,0.8,1)) x = np.linspace(-10, 10, 1000) line1, = axes.plot(x, np.sin(x)) axes.set_xlim((-10,10)) # 設(shè)置橫坐標范圍 axes.set_ylim((-2,2)) # 設(shè)置縱坐標范圍 axes.spines['right'].set_color('none') #隱藏掉右邊框線 axes.spines['top'].set_color('none') #隱藏掉左邊框線 plt.show()
2.2.6 顯示網(wǎng)格
fig = plt.figure(figsize=(6,2)) axes = fig.add_axes((0,0,0.8,1)) x = np.linspace(-10, 10, 1000) line1, = axes.plot(x, np.sin(x)) axes.set_xlim((-10,10)) # 設(shè)置橫坐標范圍 axes.set_ylim((-2,2)) # 設(shè)置縱坐標范圍 axes.grid(True) plt.show()
2.2.7 添加注釋
fig = plt.figure(figsize=(6,2)) axes = fig.add_axes((0,0,0.8,1)) x = np.linspace(-10, 10, 1000) line1, = axes.plot(x, np.sin(x)) axes.set_xlim((-10,10)) # 設(shè)置橫坐標范圍 axes.set_ylim((-2,2)) # 設(shè)置縱坐標范圍 axes.grid(True) axes.annotate('原點', xy=(0, 0), # xy是指向點的坐標 xytext=(2.5, -1.5), # xytext注釋文字的坐標 arrowprops=dict(facecolor='red')) plt.show()
3 axis
axis在matplotlib中是一種類似于坐標軸的概念,負責處理軸標簽、刻度線、刻度標簽、網(wǎng)格線的繪制。在大多數(shù)情況下,axis我們手動創(chuàng)建,在創(chuàng)建axes時會一并創(chuàng)建axis,通過axes的實例對象即可調(diào)用axes內(nèi)的axis實例。通過axis實例,我們可以實現(xiàn)更加多樣化、細微的圖標操作。
通過axes實例可以調(diào)用get_xaxis()方法獲取axis實例,然后實現(xiàn)對label等對象的操作。
3.1 axis常用設(shè)置
3.1.1 設(shè)置坐標軸名稱
fig = plt.figure(figsize=(4,2), facecolor='grey') axes = fig.add_axes((0, 0,1,1)) # x軸 axes.get_xaxis().get_label().set_text('x axis') axes.get_xaxis().get_label().set_color('red') axes.get_xaxis().get_label().set_fontsize(16) # y軸 axes.yaxis.get_label().set_text('y axis') axes.yaxis.get_label().set_color('blue') axes.yaxis.get_label().set_fontsize(16) plt.show()
3.1.2 設(shè)置坐標軸刻度標簽樣式
fig = plt.figure(figsize=(4,2), facecolor='grey') axes = fig.add_axes((0, 0,1,1)) # 設(shè)置x軸刻度標簽 for tl in axes.get_xaxis().get_ticklabels(): tl.set_color('red') tl.set_rotation(45) tl.set_fontsize(16) plt.show()
3.1.3 設(shè)置坐標軸刻度位置
import matplotlib.ticker as ticker # Fixing random state for reproducibility np.random.seed(19680801) fig, ax = plt.subplots() ax.plot(100*np.random.rand(20)) formatter = ticker.FormatStrFormatter('$%1.2f') ax.yaxis.set_major_formatter(formatter) for tick in ax.yaxis.get_major_ticks(): tick.label1.set_visible(False) tick.label2.set_visible(True) tick.label2.set_color('green') plt.show()
3.1.4 設(shè)置坐標軸位置
fig = plt.figure(figsize=(6,2)) axes = fig.add_axes((0,0,0.8,1)) x = np.linspace(-10, 10, 1000) line1, = axes.plot(x, np.sin(x)) axes.set_xlim((-10,10)) # 設(shè)置橫坐標范圍 axes.set_ylim((-2,2)) # 設(shè)置縱坐標范圍 axes.spines['right'].set_color('none') #隱藏掉右邊框線 axes.spines['top'].set_color('none') #隱藏掉左邊框線 axes.xaxis.set_ticks_position('bottom') #設(shè)置坐標軸位置 axes.yaxis.set_ticks_position('left') #設(shè)置坐標軸位置 axes.spines['bottom'].set_position(('data', 0)) #綁定坐標軸位置,data為根據(jù)數(shù)據(jù)自己判斷 axes.spines['left'].set_position(('data', 0)) plt.show()
4 總結(jié)
本文主要介紹matplotlib圖表的三種容器元素:figure、axes、axis。figure是最底層的容器,相當于一張畫布,在畫布上,我們可以畫多個axes,axes就是figure上的子圖,每個axes都是一張獨立的圖表,每個axes包含多個axis,通過axis我們可以實現(xiàn)對圖表更多細節(jié)上的操作。
理解了matplotlib圖表三個層次的布局,我們就可以通過figure -> axes --> axis的流程完成圖表在宏觀層面的創(chuàng)建。在后續(xù)的博客中,將會繼續(xù)介紹對圖表更多更加細節(jié)化的設(shè)置以及如何畫各種不同的統(tǒng)計圖表。
參考
以上就是python Matplotlib數(shù)據(jù)可視化(2):詳解三大容器對象與常用設(shè)置的詳細內(nèi)容,更多關(guān)于Matplotlib數(shù)據(jù)可視化(2):三大容器對象與常用設(shè)置的資料請關(guān)注腳本之家其它相關(guān)文章!
- Python數(shù)據(jù)可視化編程通過Matplotlib創(chuàng)建散點圖代碼示例
- 通過python的matplotlib包將Tensorflow數(shù)據(jù)進行可視化的方法
- Python數(shù)據(jù)可視化教程之Matplotlib實現(xiàn)各種圖表實例
- python Matplotlib數(shù)據(jù)可視化(1):簡單入門
- Python數(shù)據(jù)可視化之用Matplotlib繪制常用圖形
- python數(shù)據(jù)可視化之matplotlib.pyplot基礎(chǔ)以及折線圖
- Python 數(shù)據(jù)可視化之Matplotlib詳解
- Python利用matplotlib模塊數(shù)據(jù)可視化繪制3D圖
- Python數(shù)據(jù)可視化之使用matplotlib繪制簡單圖表
- Python數(shù)據(jù)分析應(yīng)用之Matplotlib數(shù)據(jù)可視化詳情
相關(guān)文章
python 二維數(shù)組90度旋轉(zhuǎn)的方法
今天小編就為大家分享一篇python 二維數(shù)組90度旋轉(zhuǎn)的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-01-01python+mongodb數(shù)據(jù)抓取詳細介紹
這篇文章主要介紹了python+mongodb數(shù)據(jù)抓取詳細介紹,具有一定參考價值,需要的朋友可以了解下。2017-10-10對Python 兩大環(huán)境管理神器 pyenv 和 virtualenv詳解
今天小編就為大家分享一篇對Python 兩大環(huán)境管理神器 pyenv 和 virtualenv詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-12-12python網(wǎng)絡(luò)爬蟲學(xué)習筆記(1)
這篇文章主要為大家詳細介紹了python網(wǎng)絡(luò)爬蟲學(xué)習筆記的第一篇,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-04-04django創(chuàng)建最簡單HTML頁面跳轉(zhuǎn)方法
今天小編就為大家分享一篇django創(chuàng)建最簡單HTML頁面跳轉(zhuǎn)方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-08-08