接觸了很久的matplotlib,其實(shí)對(duì)figure,axes,axis的理解比較模糊
這張圖經(jīng)常見到,來自matplotlib.org

image.png
這里總結(jié)個(gè)人心得,僅供參考。
1.fig
畫畫的前提是需要一個(gè)畫板,那么plt.figure則是建立一張畫板fig,以后所有的操作都是在這個(gè)fig上進(jìn)行。建立的時(shí)候可以設(shè)置圖片的大小figsize, 和分辨率dpi
fig = plt.figure(num=1,figsize=(7.5, 7.5),dpi=350) #長7.5x寬7.5, 分辨率dpi=350
#num可以指定你的畫板,循環(huán)的時(shí)候可用
2.axes
我們可以在畫板fig上建立畫畫的區(qū)域(畫布),該區(qū)域可大可小,可panel分布,可重疊。建立axes方法很多
法1:利用fig.add_subplot
ax1 = fig.add_subplot(221)#2行2列左上角
ax2 = fig.add_subplot(222)#2行2列右上角
ax3 = fig.add_subplot(223)#2行2列左下角
ax4 = fig.add_subplot(224)#2行2列右下角
法2, 利用fig.add_axes自定義位置
以下是在x=0.2,y=0.17處建立了一個(gè)長0.68寬0.7的axes。平面地圖的南海區(qū)域就是該方法實(shí)現(xiàn)
ax = fig.add_axes([0.2, 0.17, 0.68, 0.7])
如果是要畫平面地圖,則需要在axes中添加投影方式crs
ax = plt.axes(axlevel, projection=ccrs.PlateCarree())
#set_extent需要配置相應(yīng)的crs,否則出來的地圖范圍不準(zhǔn)確
ax.set_extent(box,crs=ccrs.PlateCarree()) #box=[70,140,15,55] 為邊界經(jīng)緯度
3. axis
axis是圖的x軸和y軸相關(guān)的信息。
設(shè)置axis軸的大小刻度
ax.xaxis.set_major_locator(MultipleLocator(1.000))
ax.xaxis.set_minor_locator(AutoMinorLocator(4))
ax.yaxis.set_major_locator(MultipleLocator(1.000))
ax.yaxis.set_minor_locator(AutoMinorLocator(4))
ax.xaxis.set_minor_formatter("{x:.2f}")
如果是平面地圖,需要將x y軸的標(biāo)簽定義成地理坐標(biāo)標(biāo)簽格式
ax.set_xticks(np.arange(leftlon,rightlon+10,10), crs=ccrs.PlateCarree())
ax.set_yticks(np.arange(lowerlat,upperlat+10,10), crs=ccrs.PlateCarree())
lon_formatter = cticker.LongitudeFormatter()
lat_formatter = cticker.LatitudeFormatter()
ax.xaxis.set_major_formatter(lon_formatter)
ax.yaxis.set_major_formatter(lat_formatter)
設(shè)置x,y軸的范圍
ax.set_xlim(0, 4)
ax.set_ylim(0, 4)
設(shè)置x,y軸名稱
ax.set_xlabel("x Axis label", fontsize=14)
ax.set_ylabel("y Axis label", fontsize=14)
設(shè)置坐標(biāo)軸spine是否可見
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
官網(wǎng)例子
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
from matplotlib.patheffects import withStroke
from matplotlib.ticker import AutoMinorLocator, MultipleLocator
royal_blue = [0, 20/256, 82/256]
# make the figure
np.random.seed(19680801)
X = np.linspace(0.5, 3.5, 100)
Y1 = 3+np.cos(X)
Y2 = 1+np.cos(1+X/0.75)/2
Y3 = np.random.uniform(Y1, Y2, len(X))
fig = plt.figure(figsize=(7.5, 7.5))
ax = fig.add_axes([0.2, 0.17, 0.68, 0.7], aspect=1)
ax.xaxis.set_major_locator(MultipleLocator(1.000))
ax.xaxis.set_minor_locator(AutoMinorLocator(4))
ax.yaxis.set_major_locator(MultipleLocator(1.000))
ax.yaxis.set_minor_locator(AutoMinorLocator(4))
ax.xaxis.set_minor_formatter("{x:.2f}")
ax.set_xlim(0, 4)
ax.set_ylim(0, 4)
ax.tick_params(which='major', width=1.0, length=10, labelsize=14)
ax.tick_params(which='minor', width=1.0, length=5, labelsize=10,
labelcolor='0.25')
ax.grid(linestyle="--", linewidth=0.5, color='.25', zorder=-10)
ax.plot(X, Y1, c='C0', lw=2.5, label="Blue signal", zorder=10)
ax.plot(X, Y2, c='C1', lw=2.5, label="Orange signal")
ax.plot(X[::3], Y3[::3], linewidth=0, markersize=9,
marker='s', markerfacecolor='none', markeredgecolor='C4',
markeredgewidth=2.5)
ax.set_title("Anatomy of a figure", fontsize=20, verticalalignment='bottom')
ax.set_xlabel("x Axis label", fontsize=14)
ax.set_ylabel("y Axis label", fontsize=14)
ax.legend(loc="upper right", fontsize=14)
# Annotate the figure
def annotate(x, y, text, code):
# Circle marker
c = Circle((x, y), radius=0.15, clip_on=False, zorder=10, linewidth=2.5,
edgecolor=royal_blue + [0.6], facecolor='none',
path_effects=[withStroke(linewidth=7, foreground='white')])
ax.add_artist(c)
# use path_effects as a background for the texts
# draw the path_effects and the colored text separately so that the
# path_effects cannot clip other texts
for path_effects in [[withStroke(linewidth=7, foreground='white')], []]:
color = 'white' if path_effects else royal_blue
ax.text(x, y-0.2, text, zorder=100,
ha='center', va='top', weight='bold', color=color,
style='italic', fontfamily='Courier New',
path_effects=path_effects)
color = 'white' if path_effects else 'black'
ax.text(x, y-0.33, code, zorder=100,
ha='center', va='top', weight='normal', color=color,
fontfamily='monospace', fontsize='medium',
path_effects=path_effects)
annotate(3.5, -0.13, "Minor tick label", "ax.xaxis.set_minor_formatter")
annotate(-0.03, 1.0, "Major tick", "ax.yaxis.set_major_locator")
annotate(0.00, 3.75, "Minor tick", "ax.yaxis.set_minor_locator")
annotate(-0.15, 3.00, "Major tick label", "ax.yaxis.set_major_formatter")
annotate(1.68, -0.39, "xlabel", "ax.set_xlabel")
annotate(-0.38, 1.67, "ylabel", "ax.set_ylabel")
annotate(1.52, 4.15, "Title", "ax.set_title")
annotate(1.75, 2.80, "Line", "ax.plot")
annotate(2.25, 1.54, "Markers", "ax.scatter")
annotate(3.00, 3.00, "Grid", "ax.grid")
annotate(3.60, 3.58, "Legend", "ax.legend")
annotate(2.5, 0.55, "Axes", "fig.subplots")
annotate(4, 4.5, "Figure", "plt.figure")
annotate(0.65, 0.01, "x Axis", "ax.xaxis")
annotate(0, 0.36, "y Axis", "ax.yaxis")
annotate(4.0, 0.7, "Spine", "ax.spines")
# frame around figure
fig.patch.set(linewidth=4, edgecolor='0.5')
plt.show()