MPL-02:使用Figure與Axes座標軸管理
作者:楊強,單位:馬哥教育講師
本主題專門講解Figure的設計結構與Figure對象的應用:
1 Figure對象的創建與相關參數;
2 Figure的座標軸管理;
一、Figure對象創建與相關參數
1. 創建Figure對象
%matplotlib inline
import matplotlib.pyplot as plt
#coding=utf-8
import matplotlib.pyplot as plt
#建議不要使用Figure構造器創建Figure對象
fig=plt.figure()
fig.show(warn=False)
<Figure size 432x288 with 0 Axes>
有興趣的可以跟蹤pyplot模塊的figure函數,可以完整看見Figure的創建過程,由FigureManager創建與管理的。
默認情況下沒有Axes,就沒有圖形顯式。
2. 創建Figure對象的參數-figure函數參數
%matplotlib inline
import matplotlib.pyplot as plt
#建議不要使用Figure構造器創建Figure對象
fig=plt.figure()
fig.show(warn=False)
<Figure size 432x288 with 0 Axes>
pylot的figure函數聲明如下:
matplotlib.pyplot.figure(num=None, figsize=None, dpi=None, facecolor=None, edgecolor=None, frameon=True, FigureClass=<class 'matplotlib.figure.Figure'>, clear=False, **kwargs)
num : integer or string, optional, default: None
這是Figure的ID,類型可以是整數或者字符串,缺省值None;
|-1)如果值爲None,則創建新窗體,按照遞增方式賦值一個ID作爲num,並返回該Figure對象;
|-2)如果提供num爲整數,並且num表示的ID存在,則激活該Figure對象,並返回Figure對象的引用。
|-3)如果提供num爲整數,並且num表示的ID不存在,則創建新窗體,賦值ID爲num,並返回該Figure對象;
|-4)如果提供num爲字符串,創建方式與整數(存在與不存在)一樣,但與整數不同的是字符串num會被用來作爲窗體的標題,ID就不再是整數形式。
figsize : tuple of integers, optional, default: None
(高度,寬度)單位爲英寸,缺省值由rcParams\["figure.figsize"\] = \[6.4, 4.8\]設置
dpi : integer, optional, default: None
分辨率:每英寸的像素值。缺省值由rcParams\["figure.dpi"\] = 100設置.
facecolor :
背景顏色,可以使用元組表示,也可以使用字符表示,缺省值由rcParams\["figure.facecolor"\] = 'w'設置.
edgecolor :
邊界顏色,可以使用元組表示,也可以使用字符表示,缺省值由rcParams\["figure.edgecolor"\] = 'w'設置.
frameon : bool, optional, default: True
控制是否繪製、Figure的框架。
FigureClass : subclass of Figure
用來創建定製的Figure對象。
clear: bool, optional, default: False
如果Figure存在,則清除原來的內容,當num不存在,這個參數沒有用。
注意:
|-(1)最後一個**kwargs 參數實際說明figure函數支持matplotlib中與figure有關的所有參數。
|-(2)由於字符的顏色很難記憶,表示顏色的能力也有限,下面我採用(r,g,b,a)格式表示顏色。
%matplotlib inline
import matplotlib.pyplot as plt
#建議不要使用Figure構造器創建Figure對象
fig=plt.figure(
num='崗位分析趨勢圖',
figsize=(5.5,3.5),
dpi=100,
facecolor=(0,1,0,1),
edgecolor=(1,0,0,1),
frameon=True,
linewidth=1 #這個參數是屬於kwargs的。支持所有與figure參數有關的屬性。
)
plt.plot(1,1)
fig.show(warn=False)
在獨立窗體中顯示,需要添加一行代碼:
plt.show()
獨立窗體顯示
從上述輸出可以看出,linewidth不在其中,這個參數通過kwargs傳遞給Figure構造器。除了全局屬性,影響到Figure的參數的,需要從Figure構造器獲取。下面是Figure構造器的聲明情況:
def __init__(self,
figsize=None,
dpi=None,
facecolor=None,
edgecolor=None,
#=============================================
linewidth=0.0,
#=============================================
frameon=None,
subplotpars=None, # default to rc
tight_layout=None, # default to rc figure.autolayout
constrained_layout=None, # default to rc
#figure.constrained_layout.use
):
其中還有幾個屬性subplotspars與tight_layout,constrained_layout等幾個參數,也可以在figure函數中使用,這裏只有linewidth不在全局參數中。
注意:在figure中linewidth默認值是0。
3. 創建Figure對象的參數-全局參數
上面使用的參數,除linewidth外,實際上都可以使用全局參數來設置,這樣可以簡化每次調用figure的重複勞動。這些屬性很難記,可以通過查文檔來獲取,也可以寫一個程序來獲取這些屬性值。
與figure有關的參數:
#coding=utf-8
import matplotlib
for key in matplotlib.rcParams.keys():
if 'figure' in key:
print(key,':',matplotlib.rcParams[key])
figure.autolayout : False
figure.constrained_layout.h_pad : 0.04167
figure.constrained_layout.hspace : 0.02
figure.constrained_layout.use : False
figure.constrained_layout.w_pad : 0.04167
figure.constrained_layout.wspace : 0.02
figure.dpi : 72.0
figure.edgecolor : (1, 1, 1, 0)
figure.facecolor : (1, 1, 1, 0)
figure.figsize : [6.0, 4.0]
figure.frameon : True
figure.max_open_warning : 20
figure.subplot.bottom : 0.125
figure.subplot.hspace : 0.2
figure.subplot.left : 0.125
figure.subplot.right : 0.9
figure.subplot.top : 0.88
figure.subplot.wspace : 0.2
figure.titlesize : large
figure.titleweight : normal
下面代碼是顯示與所有linewidth有關的屬性的缺省值。
for key in matplotlib.rcParams.keys():
if 'linewidth' in key:
print(key,":",matplotlib.rcParams[key])
axes.linewidth : 0.8
boxplot.boxprops.linewidth : 1.0
boxplot.capprops.linewidth : 1.0
boxplot.flierprops.linewidth : 1.0
boxplot.meanprops.linewidth : 1.0
boxplot.medianprops.linewidth : 1.0
boxplot.whiskerprops.linewidth : 1.0
grid.linewidth : 0.8
hatch.linewidth : 1.0
lines.linewidth : 1.5
patch.linewidth : 1.0
下面使用全局參數創建Figure對象。
import matplotlib.pyplot as plt
import matplotlib as mpl
#全局參數設置
mpl.rcParams['figure.figsize']=(5.5,3.5)
mpl.rcParams['figure.dpi']=100
mpl.rcParams['figure.facecolor']=(1,1,0,1)
mpl.rcParams['figure.edgecolor']=(1,0,1,1)
mpl.rcParams['figure.frameon']=True
#創建Figure對象
fig=plt.figure(num='崗位分析趨勢圖',linewidth=3)
plt.plot(1,1)
fig.show(warn=False)
plt.show() #在不需要窗體的情況下,可以不使用這種方式顯示。
二、Figure對象與座標軸
Figure對象提供兩個函數添加座標軸:
|- add_axes ( *args, **kwargs ) :返回Axes對象或者子類對象。
|- add_subplot ( *args, **kwargs ):返回axes.SubplotBase對象(也是Axes的子類)或者其他Axes的子類對象
1. 使用add_axes添加座標軸
1.1. add_axes的核心參數*args說明:
(1)rect : sequence of float
新座標參數,參數形式爲\[left, bottom, width, height\] 參數爲分數。
(2)projection : {None, 'aitoff', 'hammer', 'lambert', 'mollweide', 'polar', 'rectilinear', str}, optional
座標軸類型,使用字符串表示,缺省值是矩形線性座標軸.
(3)polar : boolean, optional
是否是極座標,True表示極座標,等價於projection='polar'.
(4)sharex, sharey : Axes, optional
指定共享其他座標軸對象的屬性,包含相同的界限(limits), 刻度(ticks), 與比例(scale)
(5)label : str
座標軸的標籤,用來唯一標示座標軸的ID,不用於顯示。
下面是一個例子:
注意:其中第一個參數,不能帶形式參數,是必須的參數值,用來指定座標的區域。
import matplotlib.pyplot as plt
#建議不要使用Figure構造器創建Figure對象
fig=plt.figure(num='崗位分析趨勢圖',linewidth=1)
axes=fig.add_axes(
[0,0,1,1],
projection='polar',#{None, 'aitoff', 'hammer', 'lambert', 'mollweide', 'polar', 'rectilinear', str}
label='座標軸標籤'
)
fig.show(warn=False)
繪製一個標準座標軸:·
import matplotlib.pyplot as plt
#建議不要使用Figure構造器創建Figure對象
fig=plt.figure(num='崗位分析趨勢圖',linewidth=1)
axes=fig.add_axes(
[0,0,1,1],
projection='rectilinear',#{None, 'aitoff', 'hammer', 'lambert', 'mollweide', 'polar', 'rectilinear', str}
label='座標軸標籤'
)
fig.show(warn=False)
【漲姿勢時刻】請大家猜猜:'aitoff', 'hammer', 'lambert', 'mollweide'都是什麼座標!
1.2.add_axes的參數**kwargs說明:
屬性
屬性描述
adjustable
{'box', 'datalim'}
agg_filter
a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha
float
anchor
2-tuple of floats or {'C', 'SW', 'S', 'SE', ...}
animated
bool
aspect
{'auto', 'equal'} or num
autoscale_on
bool
autoscalex_on
bool
autoscaley_on
bool
axes_locator
Callable[[Axes, Renderer], Bbox]
axisbelow
bool or 'line'
clip_box
Bbox
clip_on
bool
clip_path
[(Path, Transform) | Patch\
None]
contains
callable
facecolor
color
fc
color
figure
Figure
frame_on
bool
gid
str
in_layout
bool
label
object
navigate
bool
navigate_mode
unknown
path_effects
AbstractPathEffect
picker
None or bool or float or callable
position
[left, bottom, width, height] or Bbox
rasterization_zorder
float or None
rasterized
bool or None
sketch_params
(scale: float, length: float, randomness: float)
snap
bool or None
title
str
transform
Transform
url
str
visible
bool
xbound
unknown
xlabel
str
xlim
(left: float, right: float)
xmargin
float greater than -0.5
xscale
{"linear", "log", "symlog", "logit", ...}
xticklabels
List[str]
xticks
list
ybound
unknown
ylabel
str
ylim
(bottom: float, top: float)
ymargin
float greater than -0.5
yscale
{"linear", "log", "symlog", "logit", ...}
yticklabels
List[str]
yticks
list
zorder
float
【例子-1】:指定標題(title)例子
import matplotlib.pyplot as plt
#建議不要使用Figure構造器創建Figure對象
fig=plt.figure('技術趨勢圖')
ax1=fig.add_axes(
[0.1,0.1,0.8,0.8],label='趨勢圖',projection="rectilinear",
fc=(1,0,0,1),
title="趨勢圖"
)
fig.show(warn=False)
plt.show()
其中漢字問題的解決幫辦法:
(1**)獲取字體配置文件與目錄;
(2)拷貝漢字字體文件到配置下面字體庫目錄一般是fonts/ttf目錄;
(3)修改配置文件:
下面是獲取字體配置與存放目錄代碼:
import matplotlib as mpl
#獲取配置文件
print(mpl.get_configdir())
print(mpl.matplotlib_fname())
/Users/yangqiang/.matplotlib
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/mpl-data/matplotlibrc
使用的是msyh.ttf字體文件效果
下面是使用代碼控制字體:(由於ipython緩衝的原因,如果沒有效果,建議重啓ipython notebook!)
import matplotlib.pyplot as plt
import matplotlib
#建議不要使用Figure構造器創建Figure對象
matplotlib.rcParams['font.family']='Microsoft Yahei'
fig=plt.figure('技術趨勢圖')
ax1=fig.add_axes(
[0.1,0.1,0.8,0.8],label='趨勢圖',projection="rectilinear",
fc=(1,0,0,1),
title="趨勢圖"
)
fig.show(warn=False)
plt.show()
【例子-2】:座標軸指定標尺(xlabel,xlim,xscale)的例子
import matplotlib.pyplot as plt
#建議不要使用Figure構造器創建Figure對象
fig=plt.figure('技術趨勢圖')
ax1=fig.add_axes(
[0.1,0.1,0.8,0.8],
title="趨勢圖",
xlabel='x座標',ylabel='y座標',
xlim=(0.2,0.6),ylim=(0.4,0.6),
xscale='log',yscale='linear',
)
fig.show(warn=False)
plt.show()
【例子-3】:座標軸指定刻度(xticklabels)的例子
當指定scale的值爲一些特殊的值,下面幾個屬性就可能沒有效果,所以下面例子設置xscale與yscale的值需要小心點。在下面例子中,把xscale指定爲log模式,就不會顯示刻度。
import matplotlib.pyplot as plt
#建議不要使用Figure構造器創建Figure對象
fig=plt.figure('技術趨勢圖')
ax1=fig.add_axes(
[0.1,0.1,0.8,0.8],
title="趨勢圖",
xlabel='x座標',ylabel='y座標',
xlim=(0.2,0.6),ylim=(0.4,0.6),
xscale='log',yscale='linear',
xticklabels=['a','b','c','d','e'],yticklabels=['A','B','C','D','E','F']
)
fig.show(warn=False)
plt.show()
【例子-4】使用邊界(margin)的例子
import matplotlib.pyplot as plt
#建議不要使用Figure構造器創建Figure對象
fig=plt.figure('技術趨勢圖')
ax1=fig.add_axes(
[0.1,0.1,0.8,0.8],
title="趨勢圖",
xlabel='x座標',ylabel='y座標',
#xlim=(0.2,0.6),ylim=(0.4,0.6),
xscale='log',yscale='linear',
#xticklabels=['a','b','c'],yticklabels=['A','B','C','D','E','F'],
ymargin=-0.4
)
fig.show(warn=False)
plt.show()
margin屬性效果,注意座標軸的正負
【例子-05】 使用刻度(xticks)的例子
import matplotlib.pyplot as plt
#建議不要使用Figure構造器創建Figure對象
fig=plt.figure('技術趨勢圖')
ax1=fig.add_axes(
[0.1,0.1,0.8,0.8],
title="趨勢圖",
xlabel='x座標',ylabel='y座標',
xticks=[1,2,3,4,5,6],yticks=[1,2,3],
xticklabels=['a','b','c'],
#yticklabels=['A','B','C','D','E','F'],
ymargin=-0.2
)
fig.show(warn=False)
plt.show()
座標軸的幾個屬性,相互之間是有影響的,有的是相互矛盾的,大家可以根據常理理解,掌握其中矛盾的地方。
1.3. 座標軸的刪除與添加
可以通過如下函數刪除座標軸。
|-fig.delaxes(ax)
也可以直接添加:
|-fig.add_axes(ax)
我們也可以直接使用Axes類構造座標軸對象。其中的核心參數都與上面一樣。
1.4. 使用定製構造的Axes對象
Axes的繼承結構:
|-Artist
|-_AxesBase
|-Axes
Axes的構造器定義:
class matplotlib.axes.Axes(
fig,
rect,
facecolor=None,
frameon=True,
sharex=None, sharey=None,
label='',
xscale=None, yscale=None,
**kwargs)
上面參數的含義也是顯而易見的。
#coding=utf-8
import matplotlib.pyplot as plt
fig=plt.figure('技術趨勢圖')
ax1=plt.Axes(
fig,
[0.1,0.1,0.8,0.8],
title="趨勢圖",
xlabel='x座標',ylabel='y座標',
xticks=[1,2,3,4,5,6],yticks=[1,2,3],
xticklabels=['a','b','c'],
#yticklabels=['A','B','C','D','E','F'],
ymargin=-0.2
)
fig.add_axes(ax1)
fig.show(warn=False)
plt.show()
使用Axes對象
2. 使用add_subplot添加座標軸
add_subplot函數本質與上面一樣,只是提供了更加靈活的方式。
(1)函數定義如下:
|-add_subplot(*args, **kwargs)
(2)調用方式如下:
|-add_subplot(nrows, ncols, index, **kwargs)
|-add_subplot(pos, **kwargs)
|-add_subplot(ax),這個函數與add_axes使用方法一樣
其他參數與add_axes函數一樣。下面直接使用例子說明三種調用方式:
2.1. add_subplot(nrows, ncols, index, **kwargs)調用方式
這三個參數用來產生多個座標軸,座標軸個數有nrows * ncols;
|-nrows:座標軸個數的行數
|-ncols:座標軸個數的列數
|-index:座標軸的位置
位置下標從1開始
#coding=utf-8
import matplotlib.pyplot as plt
fig=plt.figure('技術趨勢圖')
fig.add_subplot(2,2,1)
fig.add_subplot(2,2,2)
fig.add_subplot(2,2,3)
fig.add_subplot(2,2,4)
fig.show(warn=False)
plt.show()
多個座標軸
2.2. add_subplot(pos, **kwargs)調用方式
pos參數用來產生多個座標軸,pos必須是三位數的整數, ,,;
|-第一位數表示nrows
|-第二位數表示ncols
|-第三位數表示index
#coding=utf-8
import matplotlib.pyplot as plt
fig=plt.figure('技術趨勢圖')
fig.add_subplot(221)
fig.add_subplot(222)
fig.add_subplot(223)
fig.add_subplot(224)
fig.show(warn=False)
plt.show()
使用pos形式的參數
2.2. 座標佔多行與多列的情況
【例子-1】佔兩列的情況
#coding=utf-8
import matplotlib.pyplot as plt
fig=plt.figure('技術趨勢圖')
'''
fig.add_subplot(2,2,1)
fig.add_subplot(2,2,2)
fig.add_subplot(2,2,3)
fig.add_subplot(2,2,4)
'''
fig.add_subplot(2,1,1)
fig.add_subplot(2,2,3)
fig.add_subplot(2,2,4)
fig.show(warn=False)
plt.show()
【例子-2】佔兩行的情況
#coding=utf-8
import matplotlib.pyplot as plt
fig=plt.figure('技術趨勢圖')
fig.add_subplot(1,2,1)
fig.add_subplot(2,2,2)
fig.add_subplot(2,2,4)
fig.show(warn=False)
plt.show()
【例子-3】佔兩行,第二列的情況
#coding=utf-8
import matplotlib.pyplot as plt
fig=plt.figure('技術趨勢圖')
fig.add_subplot(1,2,2)
fig.add_subplot(2,2,1)
fig.add_subplot(2,2,3)
fig.show(warn=False)
plt.show()
附錄
1. 本文的代碼列表
|-plt02_figure.py
|-plt02_Axes_cls.py
|-plt02_add_axes.py
|-plt02_add_plot.py
2. 下載地址: