matplotlib气象绘图

3823 字
19 分钟
matplotlib气象绘图

Matplotlib 绘图方法指南#

本文档系统整理了气象气候分析中常用的 matplotlib 绘图类型和多子图布局方法。


零、全局设置#

中文字体设置#

import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] # 使用黑体,解决中文乱码
plt.rcParams['axes.unicode_minus'] = False # 解决负号显示为方块的问题
参数说明
font.sans-serif设置无衬线字体列表,'SimHei'=黑体, 'Microsoft YaHei'=微软雅黑
axes.unicode_minusFalse 避免负号 - 显示为乱码方块

一、画布与坐标轴创建#

1.1 figure + add_subplot(最常用)#

fig = plt.figure(figsize=(8, 5))
ax = fig.add_subplot(1, 1, 1) # 1行1列第1个
ax = fig.add_subplot(projection=ccrs.PlateCarree(central_longitude=180)) # 地图投影
参数说明
figsize=(w, h)画布宽高(英寸)
nrows, ncols, index子图的行数、列数、当前索引(从1开始)
projection地图投影(需配合 cartopy 使用)

1.2 plt.subplots(一行创建多子图)#

fig, ax = plt.subplots() # 单子图
fig, axs = plt.subplots(2, 1, figsize=(9, 10), # 2行1列
subplot_kw={'projection': ccrs.PlateCarree(central_longitude=180)})
fig, ax = plt.subplots(nrows=3, figsize=(8, 11), # 3行
subplot_kw={'projection': ccrs.PlateCarree(central_longitude=180)})
参数说明
nrows行数
ncols列数(默认1)
figsize画布尺寸
subplot_kw传给每个子图的额外参数,常用于设置 projection

1.3 plt.axes(直接创建 axes)#

ax = plt.axes(projection=ccrs.PlateCarree(central_longitude=180))

1.4 fig.add_axes(精确定位 colorbar)#

cb_ax = fig.add_axes([0.1, 0.06, 0.4, 0.02]) # [left, bottom, width, height](相对坐标)
fig.colorbar(m1, cax=cb_ax, orientation='horizontal')

二、填色图 — contourf#

2.1 标准用法#

cf = ax.contourf(lon, lat, data, levels, cmap='RdBu_r',
extend='both', transform=ccrs.PlateCarree())
参数说明
lon, lat经纬度数组(1D或2D)
data二维数据数组 (lat, lon)
levels等值线层级,常用 np.arange(start, stop, step)np.linspace(start, stop, n)
cmap颜色映射,如 'RdBu_r'(白→红/蓝)、'bwr''jet'
extend'both'=两侧超出范围用三角标记;'max' / 'min' / 'neither'
transform坐标系转换(cartopy 地图投影时必加)

2.2 sacpy 增强版#

m = ax.scontourf(lon, lat, data, cmap='RdBu_r',
levels=np.arange(-1.2, 1.4, 0.2), extend='both')

scontourf 是 sacpy.Map 提供的增强 contourf,自动带等值线描边等特性。


三、等值线 — contour#

# 标准 contour
ax.contour(lon, lat, data, colors='grey', transform=ccrs.PlateCarree())
# sacpy 增强版:基于 contourf 对象自动添加黑边
ax.scontour(m, colors='black')
参数说明
lon, lat, data同 contourf
colors等值线颜色
linewidths线宽

scontour 需要传入一个 contourf 对象 m,自动使用 m 的 levels 来画等值线。

3.1 等值线标注 — clabel#

在等值线上直接标注数值:

cs = ax.contour(lon, lat, data, levels=levels_c,
colors='k', linewidths=0.6)
ax.clabel(cs, inline=True, fontsize=8, fmt='%d')
参数说明
cscontour() 返回的对象
inlineTrue 表示标签打断等值线后嵌入显示
fontsize标签字号
fmt标签格式:'%d' 整数、'%.1f' 一位小数
colors标签颜色(默认与等值线同色)

四、散点图 — scatter#

4.1 基本用法与常用参数#

ax.scatter(x, y,
s=50, # 点大小(面积,非直径)
c='steelblue', # 填充色
marker='o', # 形状
alpha=0.7, # 透明度
edgecolors='k', # 边缘色
linewidths=0.3, # 边缘线宽
zorder=3) # 图层叠放顺序
参数说明
x, y散点的 x、y 坐标
s点大小(面积),标量或数组
c / color颜色:'r', [0.5,0.5,0.5], 'tab:blue',或数组(配合 cmap 使用)
marker形状:'o'圆, 's'方, '^'上三角, 'D'菱形, '*'星, '+'十字, 'x'
alpha透明度 0~1
edgecolors边缘颜色,'none' 隐藏边缘, 'k' 黑色
linewidths边缘线宽
zorder图层顺序,数值越大越靠前

4.3 分组上色#

# 中间值灰色,高值红色,低值蓝色
ax.scatter(ONI, SOI, color=[0.5, 0.5, 0.5]) # 全部灰色打底
ax.scatter(ONI[ONI >= 1.5], SOI[ONI >= 1.5], color='r') # 高值红色
ax.scatter(ONI[ONI <= -1.5], SOI[ONI <= -1.5], color='b') # 低值蓝色

4.4 显著性打点#

lon2d, lat2d = np.meshgrid(lon, lat)
ax.scatter(lon2d[significant], lat2d[significant],
color='grey', s=2, transform=ccrs.PlateCarree())

条件索引 [significant] 只提取通过显著性检验的格点。

4.5 气泡图(Size + Color 双变量映射)#

通过 sc 分别映射两个变量,同时展示数据的”大小”和”强度”:

sc = ax.scatter(x, y,
s=z, # 点面积正比于 z 值
c=c_array, # 颜色映射到 c_array
cmap='viridis',
alpha=0.7,
edgecolors='gray',
linewidths=0.5)
cbar = plt.colorbar(sc, pad=0.02)
cbar.set_label('Color Variable')
参数说明
s=z点面积正比于数组 z,实现气泡大小映射
c=c_array, cmap=...根据数组值映射颜色,cmap 选择色表
cmap常用:'viridis'(感知均匀), 'coolwarm'(冷暖), 'RdBu_r'(红蓝)

4.6 散点图 + 回归拟合线 + R² 标注#

from scipy import stats
slope, intercept, r_value, p_value, std_err = stats.linregress(x, y)
# 散点
ax.scatter(x, y, s=40, c='steelblue', alpha=0.7, label='Data')
# 拟合线(x 需排序后才连线)
x_sorted = np.sort(x)
ax.plot(x_sorted, slope * x_sorted + intercept,
color='red', linewidth=1.5,
label=f'y={slope:.2f}x+{intercept:.2f}')
# R² 和 p 值文本框
ax.text(0.05, 0.95,
f'$R^2$ = {r_value**2:.3f}\np = {p_value:.2e}',
transform=ax.transAxes, fontsize=9,
verticalalignment='top',
bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.5))
参数/函数说明
stats.linregress(x, y)一元线性回归,返回 (斜率, 截距, R, p, 标准误)
r_value**2决定系数 R²
ax.text(x, y, text, transform=ax.transAxes)在图中添加文本框,transAxes 使用相对坐标 (0~1)
bbox=dict(boxstyle='round', facecolor='wheat')文本框样式:圆角 + 底色

五、折线图 — plot#

5.1 基本用法#

l1, = ax.plot(x, y, '-', c='tab:blue', linewidth=2)
参数说明
x, y坐标数据
'-'线型:'-'实线, '--'虚线, '-.'点划线, ':'点线
c / color颜色
linewidth / lw线宽
marker数据点形状:'o', 's', '^', '*', '.' 等,'None' 不显示
label图例标签(需配合 legend() 使用)

5.2 水平/垂直参考线#

ax.axhline(y=0, color='k', linestyle='-') # 水平线
ax.axhline(y=0.5, color='k', linestyle='--') # 水平虚线
ax.axvline(x=0, color='k', linestyle='-') # 垂直线
参数说明
y水平线的 y 值
x垂直线的 x 值
color颜色
linestyle线型
linewidth线宽

5.3 条件上色#

ax.plot(time_year[nino34_DJF > 0.5], nino34_DJF[nino34_DJF > 0.5], 'ro') # 高值红点
ax.plot(time_year[nino34_DJF < -0.5], nino34_DJF[nino34_DJF < -0.5], 'bo') # 低值蓝点

5.4 滑动平均(平滑曲线)#

y_smooth13 = y.rolling(window=13, center=True).mean() # 13点滑动平均
y_smooth5 = y.rolling(window=5, center=True).mean() # 5点滑动平均
ax.plot(x, y_smooth13, color='black', linewidth=1.5, label='13-point smooth')
ax.plot(x, y_smooth5, color='yellowgreen', linewidth=1.2, label='5-point smooth')
参数说明
window滑动窗口大小(点数)
center=True窗口居中(前后各取 window/2 个点)

5.5 趋势线(线性回归拟合)#

from scipy import stats
x_num = np.arange(len(y)) # 将时间转为数字索引
slope, intercept, r, p, std = stats.linregress(x_num, y)
y_fit = intercept + slope * x_num
ax.plot(x, y, color='grey', alpha=0.6, label='Raw') # 原始数据
ax.plot(x, y_fit, color='red', linewidth=2, label='Trend') # 趋势线
ax.legend()

六、矢量图 — quiver / quiverkey#

6.1 quiver 基本用法#

x_int = 3 # 经度抽取间隔(每隔几个点取一个)
y_int = 3 # 纬度抽取间隔
qv = ax.quiver(lon_wnd[::x_int], lat_wnd[::y_int],
uwnd[::y_int, ::x_int], vwnd[::y_int, ::x_int],
transform=ccrs.PlateCarree())
参数说明
X, Y箭头起点坐标(1D或2D,通常需降采样)
U, V纬向风、经向风分量
scale箭头缩放因子,数值越大箭头越短(None 自动)
width箭头杆宽度(坐标轴单位)
headwidth箭头头部宽度倍数(相对杆,默认 3)
headlength箭头头部长度倍数(相对杆,默认 5)
headaxislength箭头头部在轴线方向的长度(默认 4.5)
pivot旋转点:'tail'(尾部,默认), 'mid'(中间), 'tip'(头部)
color箭头颜色
alpha透明度
transform坐标系转换

6.2 使用 np.meshgrid 生成 2D 网格#

从 xarray 降采样后,用 meshgrid 生成 quiver 需要的 2D 坐标:

step = 3
u_plot = u_data[::step, ::step]
v_plot = v_data[::step, ::step]
lon_1d = u_plot['lon'].values
lat_1d = u_plot['lat'].values
lon2d, lat2d = np.meshgrid(lon_1d, lat_1d)
qv = ax.quiver(lon2d, lat2d, u_plot.values, v_plot.values,
scale=200, width=0.002, transform=ccrs.PlateCarree())

6.3 矢量遮罩(仅显示超过阈值的箭头)#

mask = (np.abs(U) < threshold) & (np.abs(V) < threshold)
U_masked = U.copy()
V_masked = V.copy()
U_masked[mask] = np.nan
V_masked[mask] = np.nan

6.4 图例箭头 — quiverkey#

ax.quiverkey(qv, X=0.9, Y=0.07, U=10, label='10 m/s',
labelpos='S', labelsep=0.05, coordinates='axes')
参数说明
qvquiver 返回的对象
X, Y图例位置(取决于 coordinates
U参考箭头代表的数值
label图例文字
labelpos文字位置:'S'南, 'N'北, 'E'东, 'W'西
labelsep文字与箭头的间距
coordinates'axes'=相对坐标(0~1), 'data'=数据坐标

6.5 风场图例框#

import matplotlib.patches as mpatches
w, h = 0.12, 0.12 # 矩形框尺寸
rect = mpatches.Rectangle((1-w, 0), w, h,
transform=ax.transAxes,
linewidth=1, ec='k', fc='w')
ax.add_patch(rect)
ax.quiverkey(qv, 1-w/2, 0.7*h, 10, '10 m/s',
labelpos='S', labelsep=0.05, coordinates='axes')

mpatches.Rectangle 参数:

参数说明
(x, y)左下角坐标
width, height宽高
transformax.transAxes 表示相对坐标
ec / edgecolor边框颜色
fc / facecolor填充颜色

6.6 sacpy 增强版 — squiver#

ax.squiver(uwnd.lon, uwnd.lat, uwnd_tmp, vwnd_tmp,
stepx=4, stepy=2, width=0.004)
参数说明
lon, lat坐标
u, v风速分量
stepx, stepy经向/纬向抽样间隔
width箭头宽度

七、误差棒图 — errorbar#

l1, = ax.plot(range(1, 13), clim_mean, '-', c='tab:blue', linewidth=2)
ax.errorbar(range(1, 13), clim_mean, yerr=[yerr_lower, yerr_upper],
fmt='-o', capsize=5)
参数说明
x横坐标
y纵坐标(均值)
yerr误差范围:单个值对称误差 / [lower, upper] 不对称误差
fmt格式字符串,如 '-o' 表示实线+圆点标记
capsize误差条末端横线长度
color颜色

八、填充面积图 — fill_between#

ax.fill_between(time, ts, where=(ts > 0), color='tab:red', alpha=0.8)
ax.fill_between(time, ts, where=(ts < 0), color='tab:blue', alpha=0.8)
参数说明
x横坐标
y纵坐标
where布尔条件,只填充满足条件的区域
color填充颜色
alpha透明度

常用于正负值分色填充(如 ENSO 指数暖事件红色、冷事件蓝色)。


九、矩形框标记 — 区域标注#

# Nino34 区域框
lon_min, lat_min = 190, -5
lon_max, lat_max = 240, 5
ax.plot([lon_min, lon_max], [lat_min, lat_min], linewidth=2, color='red',
transform=ccrs.PlateCarree())
ax.plot([lon_min, lon_max], [lat_max, lat_max], linewidth=2, color='red',
transform=ccrs.PlateCarree())
ax.plot([lon_min, lon_min], [lat_min, lat_max], linewidth=2, color='red',
transform=ccrs.PlateCarree())
ax.plot([lon_max, lon_max], [lat_min, lat_max], linewidth=2, color='red',
transform=ccrs.PlateCarree())

用 4 条 plot 线画出矩形框,标注特定区域(如 Nino3.4 区域)。


十、色标 — colorbar#

10.1 pyplot 模式(单图快捷)#

cbar = plt.colorbar(cf, pad=0.02)
cbar.set_label('SST (°C)')

10.2 绑定到坐标轴(子图推荐)#

cb = fig.colorbar(cf, ax=ax,
orientation='horizontal',
location='right',
pad=0.08,
shrink=0.85,
aspect=30,
extend='both',
ticks=np.arange(0, 36, 5))
cb.set_label('Temperature (°C)', fontsize=12)
cb.ax.tick_params(labelsize=12)
参数说明
cfcontourf 等返回的 mappable 对象
ax关联的子图
cax精确指定色标 Axes(与 ax 二选一)
orientation方向:'vertical'(默认)或 'horizontal'
location'right', 'left', 'top', 'bottom'
pad色标与主图的间距(相对主图尺寸的比例)
shrink色标长度的缩放比例 (0~1)
aspect色标长宽比(数值越大越细长)
extend是否显示超出范围的三角箭头,默认与 contourf 一致:'both'/'min'/'max'/'neither'
ticks手动指定刻度位置

10.3 精确定位(自定义位置)#

cb_ax = plt.axes([0.12, 0.00, 0.76, 0.04]) # [left, bottom, width, height]
cb = plt.colorbar(cf, cax=cb_ax, orientation='horizontal')
cb.set_label('Label', fontsize=8)
cb.ax.tick_params(labelsize=7)

plt.axes([l, b, w, h]) 使用图形相对坐标 (0~1) 创建色标专用 Axes。


十一、图标题与轴标签#

fig.suptitle('Title for whole figure', fontsize=20) # 全图标题
ax.set_title('Subplot Title', fontsize=16) # 子图标题
ax.set_xlabel('X Label', fontsize=16) # X 轴标签
ax.set_ylabel('Y Label', fontsize=16) # Y 轴标签
ax.legend(['Line1', 'Line2']) # 图例

十二、刻度与格式#

12.1 自定义刻度#

ax.set_xticks(range(1, 13)) # 设定刻度位置
ax.set_xticklabels(['Jan', 'Feb', ..., 'Dec']) # 设定刻度标签文字

12.2 刻度样式#

ax.tick_params(labelsize=14) # 统一设置刻度标签大小
plt.xticks(fontsize=14) # X 轴刻度字体
plt.yticks(fontsize=14) # Y 轴刻度字体

12.3 cartopy 地图刻度格式化#

ax.xaxis.set_major_formatter(LongitudeFormatter())
ax.yaxis.set_major_formatter(LatitudeFormatter())

12.4 坐标轴范围#

ax.set_xlim([time[0], time[-1]]) # X 轴范围
ax.set_ylim([-2, 2.5]) # Y 轴范围
ax.axis([-3.5, 3.5, -6.5, 6.5]) # [xmin, xmax, ymin, ymax]

12.5 手动自定义经纬度标签#

不依赖 LongitudeFormatter,手动用 set_xticklabels 生成 120°E / 60°W 格式:

xticks = np.arange(0, 360, 30)
ax.set_xticks(xticks, crs=ccrs.PlateCarree())
ax.set_xticklabels([
"0°" if x == 0
else "180°" if x == 180
else f"{int(x)}°E" if 0 < x < 180
else f"{int(360 - x)}°W"
for x in xticks
], fontsize=6)
yticks = np.arange(-90, 91, 30)
ax.set_yticks(yticks, crs=ccrs.PlateCarree())
ax.set_yticklabels([
f"{int(abs(y))}°N" if y > 0
else ("0°" if y == 0 else f"{int(abs(y))}°S")
for y in yticks
], fontsize=6)

十三、网格线#

ax.grid() # 普通网格
ax.gridlines() # cartopy 地图网格

十四、多子图布局#

14.1 模式一:n 行 × 1 列#

fig, ax = plt.subplots(nrows=3, figsize=(8, 11),
subplot_kw={'projection': ccrs.PlateCarree(central_longitude=180)})
for i in range(3):
ax[i].contourf(...) # ax[i] 访问第 i 个子图

14.2 模式二:混合布局(左地图 + 右折线)#

fig = plt.figure(figsize=[9, 10])
for i in range(3):
ax = fig.add_subplot(3, 2, 2*i+1, # 第1,3,5 位置 — 地图
projection=ccrs.PlateCarree(central_longitude=180))
# ... 画填色图 ...
ax = fig.add_subplot(3, 2, 2*i+2) # 第2,4,6 位置 — 折线图
# ... 画时间序列 ...
cb_ax = fig.add_axes([0.1, 0.06, 0.4, 0.02]) # 底部色标
fig.colorbar(m1, cax=cb_ax, orientation='horizontal')

技巧add_subplot(R, C, N) 中 N 从 1 开始,按行编号。地图和折线交替排列。

14.3 模式三:单行多子图(共用色标)#

fig, ax = fig.add_subplot(1, 1, 1) # 单子图

14.4 子图间距调整#

plt.subplots_adjust(left=0.05, right=0.95, top=0.95, bottom=0.05,
hspace=0.4, wspace=0.3)
参数说明
left, right, top, bottom画布边距(相对值 0~1)
hspace子图间垂直间距
wspace子图间水平间距

十五、图片保存#

fig.savefig('output.png', dpi=300, format='png')
plt.savefig('output.png', dpi=300, format='png')
参数说明
fname输出文件名
dpi分辨率(每英寸点数),300 适合出版级
format格式:'png', 'pdf', 'svg', 'jpg'

十六、sacpy.Map 专用绘图方法汇总#

方法功能等效 matplotlib
ax.scontourf(lon, lat, data, ...)增强填色图ax.contourf()
ax.scontour(m, colors=...)基于填色图的等值线ax.contour()
ax.squiver(lon, lat, u, v, ...)增强矢量图ax.quiver()
ax.sig_plot(lon, lat, p_value, thrshd, color)显著性打点ax.scatter()
ax.init_map(stepx, stepy, smallx, smally)初始化地图刻度和外观组合设置

十七、柱状图 — bar#

plt.figure(figsize=(10, 3.5), dpi=150)
# 正值柱(红色)
plt.bar(x[y >= 0], y[y >= 0],
width=30, color='lightcoral', edgecolor='none')
# 负值柱(蓝色)
plt.bar(x[y < 0], y[y < 0],
width=30, color='lightblue', edgecolor='none')
plt.axhline(0, color='k', linewidth=0.8) # 零线
plt.ylabel('WP Index')
plt.title('WP Index (1979–2025)')
# 自定义刻度标签
years = pd.date_range(start=x.min(), end=x.max(), freq='5YS')
plt.xticks(years, [d.year for d in years])
plt.tight_layout()
参数说明
x柱子的 x 坐标(位置)
height(第二个位置参数)柱子的高度(y 值)
width柱子的宽度,单位与 x 轴相同
color填充颜色
edgecolor边框颜色,'none' 无边框
align对齐方式:'center'(默认)/ 'edge'
bottom柱子的底部起始位置(堆叠柱状图用)

十八、显著性填色 — Hatching(影线)#

用影线图案标记通过显著性检验的区域(替代打点):

# sig 为布尔数组(True = 通过检验)
ax.contourf(lon, lat, sig,
levels=[0.5, 1.5], # 区分 False(0) 和 True(1)
hatches=['..'], # 影线图案
colors='none', # 不填充颜色,仅显示影线
transform=ccrs.PlateCarree())
参数说明
levels必须设为 [0.5, 1.5] 以区分布尔值
hatches影线样式列表
colors='none'填充透明,只显示影线

常用影线图案:

图案效果图案效果
'/'斜线'\\'反斜线
'.'稀疏点'..'密点
'x'叉号'+'加号
'o'圆圈'*'星号

十九、图例 — legend#

# 自动图例(需在 plot/bar 时指定了 label)
ax.legend()
# 指定位置与样式
ax.legend(loc='upper right', frameon=False, fontsize=9,
ncol=2, title='Legend Title', fancybox=True, shadow=True)
参数说明
loc位置:'best', 'upper right', 'upper left', 'lower right', 'lower left', 'upper center', 'lower center', 'center', 'center left', 'center right'
frameonTrue 显示边框, False 隐藏
fancybox是否圆角边框
shadow是否显示阴影
fontsize字体大小
ncol图例列数(多列排列)
title图例标题文字

二十、自动布局 — tight_layout#

plt.tight_layout() # 自动调整子图间距,防止标签重叠

在多子图或图表元素较多时,调用 tight_layout() 可自动优化间距。


二十一、常用颜色映射表(cmap)#

色表名适用场景
'RdBu_r'plt.cm.RdBu_r距平/异常场,红正蓝负(气象最常用)
'RdBu'plt.cm.RdBu蓝正红负
'bwr'蓝-白-红,适合距平
'coolwarm'冷暖色,适合温度
'jet'彩虹色通用场
'viridis'感知均匀,适合连续变量
'seismic'蓝白红,适合相关/回归场
'Spectral_r'光谱色,适合降水
'gist_ncar'气象常用高对比彩色

二十二、完整绘图流程(柱状图示例)#

# ========== 1. 导入库 ==========
import numpy as np
import matplotlib.pyplot as plt
# ========== 2. 全局设置 ==========
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
# ========== 3. 准备数据 ==========
x = np.array(['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'])
y = np.array([2.1, 3.5, 5.8, 8.2, 12.0, 15.5,
18.3, 17.0, 13.2, 8.8, 4.5, 2.8])
# ========== 4. 创建图形 ==========
fig, ax = plt.subplots(figsize=(8, 4), dpi=150)
# ========== 5. 绘制柱状图 ==========
colors = ['tab:red' if v > 10 else 'tab:blue' for v in y]
ax.bar(x, y, color=colors, edgecolor='k', linewidth=0.5)
ax.axhline(y=np.mean(y), color='k', linestyle='--',
label=f'Mean = {np.mean(y):.1f}')
# ========== 6. 标签与标题 ==========
ax.set_xlabel('Month', fontsize=12)
ax.set_ylabel('Temperature (°C)', fontsize=12)
ax.set_title('Monthly Average Temperature', fontsize=14)
ax.legend(loc='upper left', frameon=False)
ax.tick_params(labelsize=10)
ax.grid(axis='y', alpha=0.3)
# ========== 7. 调整布局并保存 ==========
plt.tight_layout()
plt.savefig('monthly_temp.png', dpi=300, bbox_inches='tight')
plt.show()

流程总结:导入 → 全局设置 → 准备数据 → 创建图形 → 绘图 → 标签/标题 → 布局调整 → 保存/显示。


快速参考速查表#

需求函数/代码
中文支持plt.rcParams['font.sans-serif'] = ['SimHei']
填色图ax.contourf(lon, lat, data, levels, cmap=...)
等值线ax.contour(lon, lat, data, colors=...)
等值线标注ax.clabel(cs, inline=True, fontsize=8, fmt='%d')
散点图ax.scatter(x, y, c=..., s=..., marker='o')
散点+回归+标注stats.linregress + ax.plot + ax.text
气泡图ax.scatter(x, y, s=z, c=c_arr, cmap=...)
折线图ax.plot(x, y, 'o-', c=..., marker=...)
滑动平均y.rolling(window=13, center=True).mean()
趋势线stats.linregress(x_num, y)ax.plot
柱状图ax.bar(x, y, width=..., color=...)
水平线ax.axhline(y=0, color='k', linestyle='--')
矢量图ax.quiver(X, Y, U, V, scale=..., transform=...)
矢量图例ax.quiverkey(qv, X, Y, U, label, labelpos=...)
误差棒ax.errorbar(x, y, yerr=[lo, hi], fmt='-o')
填充面积ax.fill_between(x, y, where=..., color=...)
显著性填色ax.contourf(lon, lat, sig, levels=[0.5,1.5], hatches=['..'], colors='none')
色标fig.colorbar(cf, ax=ax, orientation=..., shrink=...)
图例ax.legend(loc='best', frameon=False, ncol=2)
标题ax.set_title('Title', fontsize=...)
自动布局plt.tight_layout()
手动经纬度标签ax.set_xticklabels([...])
保存fig.savefig('out.png', dpi=300)
间距调整plt.subplots_adjust(hspace=0.4, wspace=0.3)

文章分享

如果这篇文章对你有帮助,欢迎分享给更多人!

matplotlib气象绘图
http://liuhuangzao.top/posts/python/matplotlib/
作者
硫磺皂
发布于
2026-07-15
许可协议
CC BY-NC-SA 4.0
Profile Image of the Author
硫磺皂
干嘛
公告
欢迎来到我的博客!这是一则示例公告。
音乐
封面

音乐

暂未播放

0:000:00
暂无歌词
分类
标签
站点统计
文章
8
分类
2
标签
5
总字数
13,914
运行时长
0
最后活动
0 天前
站点信息
构建平台
Local
博客版本
Firefly v6.13.10
文章许可
CC BY-NC-SA 4.0