用Matplotlib繪制二維圖像的最簡單方法是:
1. 導入模塊
導入matplotlib的子模塊
import matplotlib.pyplot as plt
import numpy as np
2. 獲取數據對象
給出x,y兩個數組[Python列表],注意兩個列表的元素個數必須相同,否則會報錯
x=np.array([1,2,3,4,])
y=x*2
3. 調用畫圖方法
調用pyplot模塊的繪圖方法畫出圖像,基本的畫圖方法有:plot(將各個點連成曲線圖)、scatter(畫散點圖),bar(畫條形圖)還有更多方法。
1) 新建圖畫板對象
# 使用figure()函數重新申請一個figure對象
# 注意,每次調用figure的時候都會重新申請一個figure對象
# 第一個參數表示的是編號,第二個表示的是圖表的長寬
plt.figure(num = 2, figsize=(8, 5))
2) 調用畫圖種類模式的方法
#color='red'表示線顏色,inewidth=1.0表示線寬,linestyle='--'表示線樣式
L1 , =plt.plot(x,y,color="r",linewidth=1.0, linestyle='--', label=”曲線圖”)
# s表示點的大小,默認rcParams['lines.markersize']**2
L2 , =plt.scatter(x,y,color="r",s=12,linewidth=1.0,linestyle='--',lable=”散點圖”)
L3 , =plt.bar(x,y, color='green')
3) 設置圖標簽
# 使用legend繪制多條曲線
plt.legend(handles=[L1,L2], labels=[”曲線圖”, ”散點圖”], loc=”best”)
或者:
plt.plot(x,y,lable=”label”)
plt.lengend()
4) 設置軸線的lable(標簽)
plt.xlabel('longitude')#說明x軸表示經度
plt.ylabel('latitude')#說明y軸表示緯度
5) 設置軸線取值參數范圍
plt.axis([-1,2,1,3]) # x和y參數范圍
plt.xlim((-1, 2)) # x參數范圍
plt.ylim((1, 3)) # y參數范圍
6) 設置軸線點位置的提示
# 設置點的位置
# 為點的位置設置對應的文字。
# 第一個參數是點的位置,第二個參數是點的文字提示。
plt.xticks(x,[r"one",r"two",r"three",r"four"])
plt.yticks(y,[r"first",r"second",r"thrid",r"fourth"])
7) 設置邊框顏色
# gca = 'get current axis'
ax = plt.gca()
# 將右邊和上邊的邊框(脊)的顏色去掉
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
8) 綁定x軸和y軸
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
9) 定義x軸和y軸的位置
ax.spines['bottom'].set_position(('data', 0))
ax.spines['left'].set_position(('data', 0))
10) 設置關鍵位置的提示信息
annotate語法說明 :annotate(s='str' ,xy=(x,y) ,xytext=(l1,l2) ,..)
s 為注釋文本內容
xy 為被注釋的坐標點
xytext 為注釋文字的坐標位置
xycoords 參數如下:
figure points points from the lower left of the figure 點在圖左下方
figure pixels pixels from the lower left of the figure 圖左下角的像素
figure fraction fraction of figure from lower left 左下角數字部分
axes points points from lower left corner of axes 從左下角點的坐標
axes pixels pixels from lower left corner of axes 從左下角的像素坐標
axes fraction fraction of axes from lower left 左下角部分
data use the coordinate system of the object being annotated(default) 使用的坐標系統被注釋的對象(默認)
polar(theta,r) if not native ‘data’ coordinates t
extcoords 設置注釋文字偏移量
參數 | 坐標系 |
| 'figure points' | 距離圖形左下角的點數量 |
| 'figure pixels' | 距離圖形左下角的像素數量 |
| 'figure fraction' | 0,0 是圖形左下角,1,1 是右上角 |
| 'axes points' | 距離軸域左下角的點數量 |
| 'axes pixels' | 距離軸域左下角的像素數量 |
| 'axes fraction' | 0,0 是軸域左下角,1,1 是右上角 |
| 'data' | 使用軸域數據坐標系 |
arrowprops #箭頭參數,參數類型為字典dict
width the width of the arrow in points 點箭頭的寬度
headwidth the width of the base of the arrow head in points 在點的箭頭底座的寬度
headlength the length of the arrow head in points 點箭頭的長度
shrink fraction of total length to ‘shrink’ from both ends 總長度為分數“縮水”從兩端
facecolor 箭頭顏色
bbox給標題增加外框 ,常用參數如下:
boxstyle方框外形
facecolor(簡寫fc)背景顏色
edgecolor(簡寫ec)邊框線條顏色
edgewidth邊框線條大小
bbox=dict(boxstyle='round,pad=0.5', fc='yellow', ec='k',lw=1 ,alpha=0.5) #fc為facecolor,ec為edgecolor,lw為lineweight
例子:
for xy in zip(x, y):
plt.annotate("(%s,%s)" % xy, xy=xy, xytext=(-20, 10), textcoords='offset points')
11) 設置圖的標題
title常用參數:
fontsize設置字體大小,默認12,可選參數 ['xx-small', 'x-small', 'small', 'medium', 'large','x-large', 'xx-large']
fontweight設置字體粗細,可選參數 ['light', 'normal', 'medium', 'semibold', 'bold', 'heavy', 'black']
fontstyle設置字體類型,可選參數[ 'normal' | 'italic' | 'oblique' ],italic斜體,oblique傾斜
verticalalignment設置水平對齊方式 ,可選參數 : 'center' , 'top' , 'bottom' ,'baseline'
horizontalalignment設置垂直對齊方式,可選參數:left,right,center
rotation(旋轉角度)可選參數為:vertical,horizontal 也可以為數字
alpha透明度,參數值0至1之間
backgroundcolor標題背景顏色
bbox給標題增加外框 ,常用參數如下:
boxstyle方框外形
facecolor(簡寫fc)背景顏色
edgecolor(簡寫ec)邊框線條顏色
edgewidth邊框線條大小
title例子:
plt.title('Interesting Graph',fontsize='large',fontweight='bold') 設置字體大小與格式
plt.title('Interesting Graph',color='blue') 設置字體顏色
plt.title('Interesting Graph',loc ='left') 設置字體位置
plt.title('Interesting Graph',verticalalignment='bottom') 設置垂直對齊方式
plt.title('Interesting Graph',rotation=45) 設置字體旋轉角度
plt.title('Interesting',bbox=dict(facecolor='g', edgecolor='blue', alpha=0.65 )) 標題邊框
plt.title('Title')
12) 設置圖的文本
text語法說明
text(x,y,string,fontsize=15,verticalalignment="top",horizontalalignment="right")
x,y:表示坐標值上的值
string:表示說明文字
fontsize:表示字體大小
verticalalignment:垂直對齊方式 ,參數:[ ‘center’ | ‘top’ | ‘bottom’ | ‘baseline’ ]
horizontalalignment:水平對齊方式 ,參數:[ ‘center’ | ‘right’ | ‘left’ ]
xycoords選擇指定的坐標軸系統:
figure points points from the lower left of the figure 點在圖左下方
figure pixels pixels from the lower left of the figure 圖左下角的像素
figure fraction fraction of figure from lower left 左下角數字部分
axes points points from lower left corner of axes 從左下角點的坐標
axes pixels pixels from lower left corner of axes 從左下角的像素坐標
axes fraction fraction of axes from lower left 左下角部分
data use the coordinate system of the object being annotated(default) 使用的坐標系統被注釋的對象(默認)
polar(theta,r) if not native ‘data’ coordinates t
arrowprops #箭頭參數,參數類型為字典dict
width the width of the arrow in points 點箭頭的寬度
headwidth the width of the base of the arrow head in points 在點的箭頭底座的寬度
headlength the length of the arrow head in points 點箭頭的長度
shrink fraction of total length to ‘shrink’ from both ends 總長度為分數“縮水”從兩端
facecolor 箭頭顏色
bbox給標題增加外框 ,常用參數如下:
boxstyle方框外形
facecolor(簡寫fc)背景顏色
edgecolor(簡寫ec)邊框線條顏色
edgewidth邊框線條大小
bbox=dict(boxstyle='round,pad=0.5', fc='yellow', ec='k',lw=1 ,alpha=0.5) #fc為facecolor,ec為edgecolor,lw為lineweight
例子:
plt.text(5, 10, t, fontsize=18, style='oblique', ha='center',va='top',wrap=True)
plt.text(3, 4, t, family='serif', style='italic', ha='right', wrap=True)
13) 展現結果圖
調用pyplot的show方法,顯示結果。
plt.show()
4. 解析
Matplotlib 里的常用類的包含關系為 Figure -> Axes -> (Line2D, Text, etc.)一個Figure對象可以包含多個子圖(Axes),在matplotlib中用Axes對象表示一個繪圖區域,可以理解為子圖。
可以使用subplot()快速繪制包含多個子圖的圖表,它的調用形式如下:
subplot(numRows, numCols, plotNum)
subplot將整個繪圖區域等分為numRows行* numCols列個子區域,然后按照從左到右,
從上到下的順序對每個子區域進行編號,左上的子區域的編號為1。如果numRows,numCols和plotNum這三個數都小於10的話,可以把它們縮寫為一個整數,例如subplot(323)和subplot(3,2,3)是相同的。subplot在plotNum指定的區域中創建一個軸對象。如果新創建的軸和之前創建的軸重疊的話,之前的軸將被刪除。
subplot()返回它所創建的Axes對象,我們可以將它用變量保存起來,然后用sca()交替讓它們成為當前Axes對象,並調用plot()在其中繪圖。
#coding=utf-8
import numpy as np
import matplotlib.pyplot as plt
plt.figure(1) # 創建圖表1
plt.figure(2) # 創建圖表2
ax1 = plt.subplot(211) # 在圖表2中創建子圖1
ax2 = plt.subplot(212) # 在圖表2中創建子圖2
x = np.linspace(0, 3, 100)
for i in xrange(5):
plt.figure(1) #選擇圖表1
plt.plot(x, np.exp(i*x/3))
plt.sca(ax1) #選擇圖表2的子圖1
plt.plot(x, np.sin(i*x))
plt.sca(ax2) # 選擇圖表2的子圖2
plt.plot(x, np.cos(i*x))
plt.show()
在圖表中顯示中文
matplotlib的缺省配置文件中所使用的字體無法正確顯示中文。為了讓圖表能正確顯示中文,可以有幾種解決方案。
在程序中直接指定字體。
在程序開頭修改配置字典rcParams。
修改配置文件。
面向對象畫圖
matplotlib API包含有三層,Artist層處理所有的高層結構,例如處理圖表、文字和曲線等的繪制和布局。通常我們只和Artist打交道,而不需要關心底層的繪制細節。
直接使用Artists創建圖表的標准流程如下:
創建Figure對象
用Figure對象創建一個或者多個Axes或者Subplot對象
調用Axies等對象的方法創建各種簡單類型的Artists
import matplotlib.pyplot as plt
X1 = range(0, 50)
Y1 = [num**2 for num in X1] # y = x^2
X2 = [0, 1]
Y2 = [0, 1] # y = x
Fig = plt.figure(figsize=(8,4)) # Create a `figure' instance
Ax = Fig.add_subplot(111) # Create a `axes' instance in the figure
Ax.plot(X1, Y1, X2, Y2) # Create a Line2D instance in the axes
Fig.show()
Fig.savefig("test.pdf")
1) figure語法及操作
figure(num=None, figsize=None, dpi=None, facecolor=None, edgecolor=None, frameon=True)
num:圖像編號或名稱,數字為編號 ,字符串為名稱,可以通過該參數激活不同的畫布
figsize:指定figure的寬和高,單位為英寸;
dpi參數指定繪圖對象的分辨率,即每英寸多少個像素,缺省值為80。相同的figsize,dpi越大畫布越大
facecolor:背景顏色
edgecolor:邊框顏色
frameon:是否顯示邊框,默認值True為繪制邊框,如果為False則不繪制邊框
import matplotlib.pyplot as plt
創建自定義圖像
fig=plt.figure(figsize=(4,3),facecolor='blue')
plt.show()
2) subplot創建單個子圖
subplot(nrows,ncols,sharex,sharey,subplot_kw,**fig_kw)
subplot可以規划figure划分為n個子圖,但每條subplot命令只會創建一個子圖 ,參考下面例子。
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 100)
#子圖1
plt.subplot(221)
plt.plot(x, x)
#子圖2
plt.subplot(222)
plt.plot(x, -x)
#子圖3
plt.subplot(223)
plt.plot(x, x ** 2)
plt.grid(color='r', linestyle='--', linewidth=1,alpha=0.3)
#子圖4
plt.subplot(224)
plt.plot(x, np.log(x))
plt.show()
3) subplots創建多個子圖
subplots參數與subplots相似
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 100)
#划分子圖
fig,axes=plt.subplots(2,2)
ax1=axes[0,0]
ax2=axes[0,1]
ax3=axes[1,0]
ax4=axes[1,1]
#子圖1
ax1.plot(x, x)
#子圖2
ax2.plot(x, -x)
#子圖3
ax3.plot(x, x ** 2)
ax3.grid(color='r', linestyle='--', linewidth=1,alpha=0.3)
#子圖4
ax4.plot(x, np.log(x))
plt.show()
4) add_subplot新增子圖
add_subplot是面對象figure類api,pyplot api中沒有此命令
add_subplot的參數與subplots的相似
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 100)
#新建figure對象
fig=plt.figure()
#新建子圖1
ax1=fig.add_subplot(2,2,1)
ax1.plot(x, x)
#新建子圖3
ax3=fig.add_subplot(2,2,3)
ax3.plot(x, x ** 2)
ax3.grid(color='r', linestyle='--', linewidth=1,alpha=0.3)
#新建子圖4
ax4=fig.add_subplot(2,2,4)
ax4.plot(x, np.log(x))
plt.show()
5) add_axes新增子區域
add_axes為新增子區域,該區域可以座落在figure內任意位置,且該區域可任意設置大小
add_axes參數可參考官方文檔:
http://matplotlib.org/api/_as_gen/matplotlib.figure.Figure.html#matplotlib.figure.Figure
import numpy as np
import matplotlib.pyplot as plt
#新建figure
fig = plt.figure()
# 定義數據
x = [1, 2, 3, 4, 5, 6, 7]
y = [1, 3, 4, 2, 5, 8, 6]
#新建區域ax1
#figure的百分比,從figure 10%的位置開始繪制, 寬高是figure的80%
left, bottom, width, height = 0.1, 0.1, 0.8, 0.8
# 獲得繪制的句柄
ax1 = fig.add_axes([left, bottom, width, height])
ax1.plot(x, y, 'r')
ax1.set_title('area1')
#新增區域ax2,嵌套在ax1內
left, bottom, width, height = 0.2, 0.6, 0.25, 0.25
# 獲得繪制的句柄
ax2 = fig.add_axes([left, bottom, width, height])
ax2.plot(x, y, 'b')
ax2.set_title('area2')
plt.show()
5. Matplotlib.pyplot和matplotlib.pylab的區別
pylab結合了pyplot和numpy,對交互式使用來說比較方便,既可以畫圖又可以進行簡單的計算。但是,對於一個項目來說,建議分別倒入使用
6. matplotlib中文顯示
import matplotlib.pyplot as plt
a) FontProperties方法
#coding=utf-8
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
fig = plt.figure()
font = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=14)
plt.xlabel(u"x軸", fontproperties=font)
plt.show()
b) fontproperties方法
#coding=utf-8
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
fig = plt.figure()
plt.ylabel(u"y軸", fontproperties="SimHei")
plt.show()
c) rcParams方法
#coding=utf-8
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
fig = plt.figure()
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
plt.xlabel(u"x軸")
plt.show()
d) rc方法
#coding=utf-8
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
fig = plt.figure()
font = {'family' : 'SimHei','weight' : 'bold','size' : '16'}
plt.rc('font', **font)
plt.rc('axes', unicode_minus=False)
plt.xlabel(u"x軸")
plt.show()
方式二用時才設置,且不會污染全局字體設置,更靈活
方式三、方式四不需要對字體路徑硬編碼,而且一次設置,多次使用,更方便。
【附錄】
一些中文字體的英文名
宋體 SimSun
黑體 SimHei
微軟雅黑 Microsoft YaHei
微軟正黑體 Microsoft JhengHei
新宋體 NSimSun
新細明體 PMingLiU
細明體 MingLiU
標楷體 DFKai-SB
仿宋 FangSong
楷體 KaiTi
隸書:LiSu
幼圓:YouYuan
華文細黑:STXihei
華文楷體:STKaiti
華文宋體:STSong
華文中宋:STZhongsong
華文仿宋:STFangsong
方正舒體:FZShuTi
方正姚體:FZYaoti
華文彩雲:STCaiyun
華文琥珀:STHupo
華文隸書:STLiti
華文行楷:STXingkai
華文新魏:STXinwei
6) Pyplot繪圖結構
Aritists
matplotlib API包含有三層:
backend_bases.FigureCanvas : 圖表的繪制領域
backend_bases.Renderer : 知道如何在FigureCanvas上如何繪圖
artist.Artist : 知道如何使用Renderer在FigureCanvas上繪圖
FigureCanvas和Renderer需要處理底層的繪圖操作,例如使用wxPython在界面上繪圖,或者使用PostScript繪制PDF。Artist則處理所有的高層結構,例如處理圖表、文字和曲線等的繪制和布局。通常我們只和Artist打交道,而不需要關心底層的繪制細節。
Artists分為簡單類型和容器類型兩種。簡單類型的Artists為標准的繪圖元件,例如Line2D、 Rectangle、 Text、AxesImage 等等。而容器類型則可以包含許多簡單類型的Artists,使它們組織成一個整體,例如Axis、 Axes、Figure等。
直接使用Artists創建圖表的標准流程如下:
l 創建Figure對象;
l 用Figure對象創建一個或者多個Axes或者Subplot對象;
l 調用Axies等對象的方法創建各種簡單類型的Artists。
a) Figure
Figure代表一個繪制面板,其中可以包涵多個Axes(即多個圖表)。
b) Axes
Axes表示一個圖表
一個Axes包涵:titlek, xaxis, yaxis
c) Axis
坐標軸
7) Pyplot繪圖結構的Artist的屬性
下面是Artist對象都具有的一些屬性:
alpha : 透明度,值在0到1之間,0為完全透明,1為完全不透明
animated : 布爾值,在繪制動畫效果時使用
axes : 此Artist對象所在的Axes對象,可能為None
clip_box : 對象的裁剪框
clip_on : 是否裁剪
clip_path : 裁剪的路徑
contains : 判斷指定點是否在對象上的函數
figure : 所在的Figure對象,可能為None
label : 文本標簽
picker : 控制Artist對象選取
transform : 控制偏移旋轉
visible : 是否可見
zorder : 控制繪圖順序
Artist對象的所有屬性都通過相應的 get_* 和 set_* 函數進行讀寫
fig.set_alpha(0.5*fig.get_alpha())
如果你想用一條語句設置多個屬性的話,可以使用set函數:
fig.set(alpha=0.5, zorder=2)
使用 matplotlib.pyplot.getp 函數可以方便地輸出Artist對象的所有屬性名和值。
>>> plt.getp(fig.patch)
aa = True
alpha = 1.0
animated = False
antialiased or aa = True
a) Figure
如前所述,Figure是最大的一個Aritist,它包括整幅圖像的所有元素,背景是一個Rectangle對象,用Figure.patch屬性表示。
通過調用add_subplot或者add_axes方法往圖表中添加Axes(子圖)。
PS:這兩個方法返回值類型不同
>>> fig = plt.figure()
>>> ax1 = fig.add_subplot(211)
>>> ax2 = fig.add_axes([0.1, 0.1, 0.7, 0.3])
>>> ax1
<matplotlib.axes.AxesSubplot object at 0x056BCA90>
>>> ax2
<matplotlib.axes.Axes object at 0x056BC910>
>>> fig.axes
[<matplotlib.axes.AxesSubplot object at 0x056BCA90>,
<matplotlib.axes.Axes object at 0x056BC910>]
為了支持pylab中的gca()等函數,Figure對象內部保存有當前軸的信息,因此不建議直接對Figure.axes屬性進行列表操作,而應該使用add_subplot, add_axes, delaxes等方法進行添加和刪除操作。
fig = plt.figure()
ax1 = fig.add_axes([0.1, 0.45, 0.8, 0.5])
ax2 = fig.add_axes([0.1, 0.1, 0.8, 0.2])
plt.show()
Figure對象可以擁有自己的文字、線條以及圖像等簡單類型的Artist。缺省的坐標系統為像素點,但是可以通過設置Artist對象的transform屬性修改坐標系的轉換方式。最常用的Figure對象的坐標系是以左下角為坐標原點(0,0),右上角為坐標(1,1)。下面的程序創建並添加兩條直線到fig中:
>>> from matplotlib.lines import Line2D
>>> fig = plt.figure()
>>> line1 = Line2D([0,1],[0,1], transform=fig.transFigure, figure=fig, color="r")
>>> line2 = Line2D([0,1],[1,0], transform=fig.transFigure, figure=fig, color="g")
>>> fig.lines.extend([line1, line2])
>>> fig.show()
---------------------
在Figure對象中手工繪制直線
注意為了讓所創建的Line2D對象使用fig的坐標,我們將fig.TransFigure賦給Line2D對象的transform屬性;為了讓Line2D對象知道它是在fig對象中,我們還設置其figure屬性為fig;最后還需要將創建的兩個Line2D對象添加到fig.lines屬性中去。
Figure對象有如下屬性包含其它的Artist對象:
axes : Axes對象列表
patch : 作為背景的Rectangle對象
images : FigureImage對象列表,用來顯示圖片
legends : Legend對象列表
lines : Line2D對象列表
patches : patch對象列表
texts : Text對象列表,用來顯示文字
b) Axes
Axes容器是整個matplotlib庫的核心,它包含了組成圖表的眾多Artist對象,並且有許多方法函數幫助我們創建、修改這些對象。和Figure一樣,它有一個patch屬性作為背景,
當它是笛卡爾坐標時,patch屬性是一個Rectangle對象;
當它是極坐標時,patch屬性則是Circle對象。
當你調用Axes的繪圖方法(例如plot),它將創建一組Line2D對象,並將所有的關鍵字參數傳遞給這些Line2D對象,並將它們添加進Axes.lines屬性中,最后返回所創建的Line2D對象列表:
x1 = np.linspace(0.0, 5.0)
x2 = np.linspace(0.0, 3.0)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)
ax1.patch.set_facecolor("green")
ax1.grid(True)
line1 = ax1.plot(x1, y1, 'yo-', label="Test1")
print type(line1)
print line1
line2 = ax2.plot(x2, y2, 'r.-', label='Test2')
-----
<type 'list'>
[<matplotlib.lines.Line2D object at 0x7fa3ac96e8d0>]
注意:
plot返回的是一個Line2D對象的列表,因為我們可以傳遞多組X,Y軸的數據,一次繪制多條曲線。
與plot方法類似,繪制直方圖的方法bar和繪制柱狀統計圖的方法hist將創建一個Patch對象的列表,每個元素實際上都是Patch的子類Rectangle,並且將所創建的Patch對象都添加進Axes.patches屬性中:
>>> ax = fig.add_subplot(111)
>>> n, bins, rects = ax.hist(np.random.randn(1000), 50, facecolor="blue")
>>> rects
<a list of 50 Patch objects>
>>> rects[0]
<matplotlib.patches.Rectangle object at 0x05BC2350>
>>> ax.patches[0]
<matplotlib.patches.Rectangle object at 0x05BC2350>
一般我們不會直接對Axes.lines或者Axes.patches屬性進行操作,而是調用add_line或者add_patch等方法,這些方法幫助我們完成許多屬性設置工作:
>>> fig = plt.figure()
>>> ax = fig.add_subplot(111)
>>> rect = matplotlib.patches.Rectangle((1,1), width=5, height=12)
>>> print rect.get_axes() # rect的axes屬性為空
None
>>> rect.get_transform() # rect的transform屬性為缺省值
BboxTransformTo(Bbox(array([[ 1., 1.],
[ 6., 13.]])))
>>> ax.add_patch(rect) # 將rect添加進ax
<matplotlib.patches.Rectangle object at 0x05C34E50>
>>> rect.get_axes() # 於是rect的axes屬性就是ax
<matplotlib.axes.AxesSubplot object at 0x05C09CB0>
>>> # rect的transform屬性和ax的transData相同
>>> rect.get_transform()
... # 太長,省略
>>> ax.transData
... # 太長,省略
>>> ax.get_xlim() # ax的X軸范圍為0到1,無法顯示完整的rect
(0.0, 1.0)
>>> ax.dataLim._get_bounds() # 數據的范圍和rect的大小一致
(1.0, 1.0, 5.0, 12.0)
>>> ax.autoscale_view() # 自動調整坐標軸范圍
>>> ax.get_xlim() # 於是X軸可以完整顯示rect
(1.0, 6.0)
>>> plt.show()
通過上面的例子我們可以看出,add_patch方法幫助我們設置了rect的axes和transform屬性。
下面詳細列出Axes包含各種Artist對象的屬性:
artists : Artist對象列表
patch : 作為Axes背景的Patch對象,可以是Rectangle或者Circle
collections : Collection對象列表
images : AxesImage對象列表
legends : Legend對象列表
lines : Line2D對象列表
patches : Patch對象列表
texts : Text對象列表
xaxis : XAxis對象
yaxis : YAxis對象
下面列出Axes的創建Artist對象的方法:
c) Axis
Axis容器包括坐標軸上的刻度線、刻度文本、坐標網格以及坐標軸標題等內容。刻度包括主刻度和副刻度,分別通過Axis.get_major_ticks和Axis.get_minor_ticks方法獲得。每個刻度線都是一個XTick或者YTick對象,它包括實際的刻度線和刻度文本。為了方便訪問刻度線和文本,Axis對象提供了get_ticklabels和get_ticklines方法分別直接獲得刻度線和刻度文本
>>> axis.get_ticklocs() # 獲得刻度的位置列表
array([ 1. , 1.5, 2. , 2.5, 3. ])
>>> axis.get_ticklabels() # 獲得刻度標簽列表
<a list of 5 Text major ticklabel objects>
>>> [x.get_text() for x in axis.get_ticklabels()] # 獲得刻度的文本字符串
[u'1.0', u'1.5', u'2.0', u'2.5', u'3.0']
>>> axis.get_ticklines() # 獲得主刻度線列表,圖的上下刻度線共10條
<a list of 10 Line2D ticklines objects>
>>> axis.get_ticklines(minor=True) # 獲得副刻度線列表
<a list of 0 Line2D ticklines objects>
7. 繪制圖形類型
1) 點線圖
#color='red'表示線顏色,inewidth=1.0表示線寬,linestyle='--'表示線樣式
L1 , =plt.plot(x,y,color="r",marker='+', linestyle='--',linewidth=1.0, label=”曲線圖”)
對於標注和線條的樣式,可以通過簡單的字符來表示:
以及標注和線條的顏色:
當然線條的顏色可以以其他方式定制。比如16進制的字符串('#008000')或者是RGB、RGBA元組的方式RGB or RGBA ((0,1,0,1)) 來實現不同的顏色。
2) 散點圖
# s表示點的大小,默認rcParams['lines.markersize']**2
L2 , =plt.scatter(x,y,color="r",s=12,linewidth=1.0,linestyle='--',lable=”散點圖”)
3) 條形圖
matplotlib.pyplot.bar(x, height, width=0.8, bottom=None, *, align='center', data=None, **kwargs)
參數解析
a) width :
scalar or array-like, optional。The width(s) of the bars (default: 0.8)
b) bottom :
scalar or array-like, optional。The y coordinate(s) of the bars bases (default: 0).
c) align :
{'center', 'edge'}, optional, default: 'center'
Alignment of the bars to the x coordinates:
'center': Center the base on the x positions.
'edge': Align the left edges of the bars with the x positions.
To align the bars on the right edge pass a negative width and align='edge'.
d) color :
scalar or array-like, optional
The colors of the bar faces.
e) edgecolor :
scalar or array-like, optional
The colors of the bar edges.
f) linewidth :
scalar or array-like, optional
Width of the bar edge(s). If 0, don't draw edges.
g) tick_label :
string or array-like, optional
The tick labels of the bars. Default: None (Use default numeric labels.)
h) xerr, yerr :
scalar or array-like of shape(N,) or shape(2,N), optional
If not None, add horizontal / vertical errorbars to the bar tips. The values are +/- sizes relative to the data:
scalar:
symmetric +/- values for all bars
shape(N,): symmetric +/- values for each bar
shape(2,N): Separate - and + values for each bar. First row
contains the lower errors, the second row contains the upper errors.
None: No errorbar. (Default)
See Different ways of specifying error bars for an example on the usage of xerr and yerr.
i) ecolor :
scalar or array-like, optional, default: 'black'
The line color of the errorbars.
j) capsize :
scalar, optional
The length of the error bar caps in points. Default: None, which will take the value from rcParams["errorbar.capsize"].
k) error_kw :
dict, optional
Dictionary of kwargs to be passed to the errorbar method. Values of ecolor or capsize defined here take precedence over the independent kwargs.
l) log :
bool, optional, default: False
If True, set the y-axis to be log scale.
m) orientation :
{'vertical', 'horizontal'}, optional
This is for internal use only. Please use barh for horizontal bar plots. Default: 'vertical'.
4) 水平條形圖
plt. Barh()
5) 直方圖
matplotlib.pyplot.hist(x, bins=None, range=None, density=None, weights=None, cumulative=False, bottom=None, histtype='bar', align='mid', orientation='vertical', rwidth=None, log=False, color=None, label=None, stacked=False, normed=None, *, data=None, **kwargs)
6) 堆疊圖
plt.stackplot()
7) 餅圖
plt.pie(x, explode=None, labels=None, colors=None, pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=None, radius=None, counterclock=True, wedgeprops=None, textprops=None, center=(0,0), frame=False)
x: 指定繪圖的數據
explode:指定餅圖某些部分的突出顯示,即呈現爆炸式
labels:為餅圖添加標簽說明,類似於圖例說明
colors:指定餅圖的填充色
autopct:設置百分比格式,如'%.1f%%'為保留一位小數
shadow:是否添加餅圖的陰影效果
pctdistance:設置百分比標簽與圓心的距離
labeldistance:設置各扇形標簽(圖例)與圓心的距離;
startangle:設置餅圖的初始擺放角度, 180為水平;
radius:設置餅圖的半徑大小;
counterclock:是否讓餅圖按逆時針順序呈現, True / False;
wedgeprops:設置餅圖內外邊界的屬性,如邊界線的粗細、顏色等, 如wedgeprops = {'linewidth': 1.5, 'edgecolor':'green'}
textprops:設置餅圖中文本的屬性,如字體大小、顏色等;
center:指定餅圖的中心點位置,默認為原點
frame:是否要顯示餅圖背后的圖框,如果設置為True的話,需要同時控制圖框x軸、y軸的范圍和餅圖的中心位置;
8) 箱線圖
plt.boxplot(x, notch=None, sym=None, vert=None, whis=None, positions=None, widths=None, patch_artist=None, meanline=None, showmeans=None, showcaps=None, showbox=None, showfliers=None, boxprops=None, labels=None, flierprops=None, medianprops=None, meanprops=None, capprops=None, whiskerprops=None)
x:指定要繪制箱線圖的數據;
notch:是否是凹口的形式展現箱線圖,默認非凹口;
sym:指定異常點的形狀,默認為+號顯示;
vert:是否需要將箱線圖垂直擺放,默認垂直擺放;
whis:指定上下須與上下四分位的距離,默認為1.5倍的四分位差;
positions:指定箱線圖的位置,默認為[0,1,2…];
widths:指定箱線圖的寬度,默認為0.5;
patch_artist:是否填充箱體的顏色;
meanline:是否用線的形式表示均值,默認用點來表示;
showmeans:是否顯示均值,默認不顯示;
showcaps:是否顯示箱線圖頂端和末端的兩條線,默認顯示;
showbox:是否顯示箱線圖的箱體,默認顯示;
showfliers:是否顯示異常值,默認顯示;
boxprops:設置箱體的屬性,如邊框色,填充色等;
labels:為箱線圖添加標簽,類似於圖例的作用;
filerprops:設置異常值的屬性,如異常點的形狀、大小、填充色等;
medianprops:設置中位數的屬性,如線的類型、粗細等;
meanprops:設置均值的屬性,如點的大小、顏色等;
capprops:設置箱線圖頂端和末端線條的屬性,如顏色、粗細等;
whiskerprops:設置須的屬性,如顏色、粗細、線的類型等;
9) 等高線圖
plt. Clabel()
10) 顏色和填充
11) 邊框和水平線條
8. 繪制動態圖
1) 范例
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
fig, ax = plt.subplots()
xdata, ydata = [], []
ln, = ax.plot([], [], 'r-', animated=False)
def init():
ax.set_xlim(0, 2*np.pi)
ax.set_ylim(-1, 1)
return ln,
def update(frame):
xdata.append(frame)
ydata.append(np.sin(frame))
ln.set_data(xdata, ydata)
return ln,
ani = FuncAnimation(fig, update, frames=np.linspace(0, 2*np.pi, 128),
init_func=init, blit=True)
plt.show()
ani.save('test_animation.gif',writer='imagemagick')
2) 構造函數
我們先來看看 FuncAnimation 的構造方法。
def __init__(self, fig, func, frames=None, init_func=None, fargs=None,
save_count=None, **kwargs):
fig 自然是 matplotlib 中的 figure 對象。
func 是每一次更新時所調用的方法,它是回調函數。因此,我們可以在這個方法中更新 figure 當中的 axes 中的 line2d 對象,它是動態更新 figure 的根本。
frames 代表了整個動畫過程中幀的取值范圍,而本質上是一個數據發生器。我將在后面重點講解它。
init_func 是初始函數,用來初始 figure 的畫面。
fargs 是每次附加給 func 回調函數的參數,可以為 None
save_count 是緩存的數量
除此之外,還有一些可選的參數,它們分別是
interval 是每 2 個 frame 發生的時間間隔,單位是 ms,默認值是 200.
repeat_delay 取值是數值,如果 animation 是重復播放的話,這個值就是每次播放之間的延遲時間,單位是 ms。
repeat bool 型可選參數,默認為 True,代表動畫是否會重復執行
blit bool 型可選參數,控制繪制的優化。默認是 False。
3) 着重參數分析
animation 的核心參數是 frames 和 func
frames 可以取值:iterable,int,generator 生成器函數 或者是 None。
但有個前提是,生成器要符合下面的簽名格式。
def gen_function() -> obj
func 是回調函數,它會在每次更新的時候被調用,所以我們只需要在這個函數中更新 figure 中的數值就可以了。
實際上,frames 決定了整個動畫 frame 的取值范圍,它會在 interval 時間內迭代一次,然后將值傳遞給 func,直到整個 frames 迭代完畢。
4) 保存動畫
ani.save('test_animation.gif',writer='imagemagick')
需要注意到的是,如果要保存 gif 圖像,這要求開發者電腦已經安裝了 ImageMagicK。
動畫可以保存為 gif 圖像,自然也能保存為 mp4 視頻格式。
但這要求開發者計算機已經安裝好 ffmpeg 庫,並且 save 方法中指定 writer 為 ffmpeg。