當(dāng)前有效matplotlib版本為:3.4.1。
概述
axes()函數(shù)功能與subplot()函數(shù)極其相似。都是向當(dāng)前圖像(figure)添加一個子圖(Axes),并將該子圖設(shè)為當(dāng)前子圖或者將某子圖設(shè)為當(dāng)前子圖。兩者的區(qū)別在于subplot()函數(shù)通過參數(shù)確定在子圖網(wǎng)格中的位置,而axes()函數(shù)在添加子圖位置時根據(jù)4個坐標(biāo)確定位置。
函數(shù)的定義簽名為:matplotlib.pyplot.axes(arg=None, **kwargs)
函數(shù)的調(diào)用簽名為:
# 在當(dāng)前圖像中添加一個鋪滿的子圖
plt.axes()
# 根據(jù)rect位置添加一個子圖
plt.axes(rect, projection=None, polar=False, **kwargs)
# 將ax設(shè)置為當(dāng)前子圖
plt.axes(ax)
函數(shù)的參數(shù)為:
arg : 取值為 None或四元組rect。
None:使用subplot(**kwargs)添加一個新的鋪滿窗口的子圖。
- 四元組
rect:rect = [left, bottom, width, height],使用 ~.Figure.add_axes根據(jù)rect添加一個新的子圖。
rect的取值為以左下角為繪制基準(zhǔn)點(diǎn),確定高度和寬度。rect的4個元素均應(yīng)在[0,1]之間(即以圖像比例為單位)。
projection: 控制子圖的投影方式。{None, 'aitoff', 'hammer', 'lambert', 'mollweide', 'polar', 'rectilinear', str},默認(rèn)值為None ,即'rectilinear'。
polar:相當(dāng)于設(shè)置projection='polar'。可選參數(shù)。布爾值,默認(rèn)值為True。
sharex, sharey:用于設(shè)置共享x/y軸。可選參數(shù)。Axes對象。默認(rèn)值為None。
lables:返回的子圖對象的標(biāo)簽。可選參數(shù)。字符串。
**kwargs:用于向創(chuàng)建子圖網(wǎng)格時用到的 ~matplotlib.gridspec.GridSpec類的構(gòu)造函數(shù)傳遞關(guān)鍵字參數(shù)。可選參數(shù)。字典。
函數(shù)的返回值為:
.axes.SubplotBase實例,或其他~.axes.Axes的子類實例。
函數(shù)原理
axes函數(shù)其實是Figure.add_subplot和Figure.add_axes方法的封裝。源碼為:
def axes(arg=None, **kwargs):
fig = gcf()
if arg is None:
return fig.add_subplot(**kwargs)
else:
return fig.add_axes(arg, **kwargs)
案例:使用axes函數(shù)添加子圖
根據(jù)輸出可知,axes添加的子圖是可以重疊的。

案例:混合應(yīng)用subplot、subplots、subplot2grid、axes函數(shù)

import matplotlib.pyplot as plt
# 添加3行3列子圖9個子圖
fig, axes = plt.subplots(3, 3)
# 為第1個子圖繪制圖形
axes[0, 0].bar(range(1, 4), range(1, 4))
# 使用subplot函數(shù)為第5個子圖繪制圖形
plt.subplot(335)
plt.plot(1,'o')
# 使用subplot2grid函數(shù)將第三行子圖合并為1個
plt.subplot2grid((3,3),(2,0),colspan=3)
# 在圖像0.5,0.5位置添加一個0.1寬0.1長的背景色為黑色的子圖
plt.axes((0.5,0.5,0.1,0.1),facecolor='k')
plt.show()
axes函數(shù)與subplot、subplots、subplot2grid函數(shù)的對比
相同之處:
axes函數(shù)與subplot、subplot2grid函數(shù)都是添加一個子圖。
不同之處:
axes函數(shù)可在圖像中的任意位置添加子圖。subplot、subplots、subplot2grid函數(shù)只能根據(jù)固定的子圖網(wǎng)格位置添加子圖。
axes函數(shù)創(chuàng)建的子圖可重疊。subplot、subplots、subplot2grid函數(shù)創(chuàng)建的子圖如果位置重疊,會覆蓋掉原有的子圖(刪除原有子圖)。
到此這篇關(guān)于matplotlib 向任意位置添加一個子圖(axes)的文章就介紹到這了,更多相關(guān)matplotlib任意位置添加子圖內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- matplotlib之pyplot模塊實現(xiàn)添加子圖subplot的使用
- matplotlib給子圖添加圖例的方法