You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

应用Cartopy投影时Matplotlib的figsize参数不生效问题

问题描述

应用Cartopy的Lambert方位等面积投影后,修改figsize参数无法影响实际图表大小;即使设置figsize=(10,10)(宽高相等),生成的图表也未呈现正方形比例。

相关初始化代码片段:

proj = ccrs.LambertAzimuthalEqualArea(central_latitude = clat, central_longitude = clon)
fig,axes = plt.subplots(1,3, figsize=(10,10),subplot_kw={'projection':proj})

补充:以下是完整代码,绘图参数从本地plot_params.json文件读取:

import json
from matplotlib import pyplot as plt
import cartopy.crs as ccrs

with open('plot_params.json', 'r') as f:
    plot_params = json.load(f)

glon_e3d = plot_params['glon_e3d']
gclat_e3d = plot_params['gclat_e3d']
glon_test = plot_params['glon_test']
gclat_test = plot_params['gclat_test']
lon_secs = plot_params['lon_secs']
lat_secs = plot_params['lat_secs']

proj = ccrs.LambertAzimuthalEqualArea(central_latitude = clat, central_longitude = clon)
fig,axes = plt.subplots(1,3, figsize=(10,10),subplot_kw={'projection':proj})
axs = axes.ravel()

extent = [205, 225, 63, 69]
ax = axs[0]
ax.gridlines()
ax.set_extent(extent, crs=ccrs.PlateCarree())
ax.scatter(glon_e3d, gclat_e3d, transform = ccrs.Geodetic(), c = 'r', marker = '.', label = 'data points', s=10)

ax = axs[1]
ax.gridlines()
ax.set_extent(extent, crs=ccrs.PlateCarree())
ax.scatter(glon_test, gclat_test, transform = ccrs.Geodetic(), c = 'r', marker = '.', label = 'data points', s=10)

ax = axs[2]
ax.gridlines()
ax.set_extent(extent, crs=ccrs.PlateCarree())
ax.scatter(lon_secs, lat_secs, transform = ccrs.Geodetic(), c = 'r', marker = '.', label = 'data points', s=10)

plt.show()

生成的图表:
生成的图表


解决方法

Cartopy投影轴会根据你设置的extent自动调整宽高比,以匹配地理区域的实际比例,这会覆盖figsize的比例设置。可以通过以下方式解决:

1. 手动指定轴的宽高比

在设置extent后,给每个轴设置固定宽高比,比如强制正方形(注意:可能导致地理区域变形):

for ax in axs:
    ax.set_extent(extent, crs=ccrs.PlateCarree())
    ax.set_aspect('equal', adjustable='box')

2. 根据地理区域比例调整figsize

先计算目标地理区域的经纬度跨度,结合投影特性调整figsize,既能保持地理区域比例正确,又能匹配预期的图表尺寸:

# 计算extent的经纬度跨度
lon_span = extent[1] - extent[0]
lat_span = extent[3] - extent[2]

# 计算适合的宽高比(Lambert方位投影下,纬度方向的视觉跨度与经度跨度的比值)
aspect_ratio = lat_span / lon_span
# 1行3列布局,所以fig宽度为高度 × 列数 × 宽高比
fig_height = 10
fig_width = fig_height * 3 * aspect_ratio

# 用调整后的figsize创建画布
fig,axes = plt.subplots(1,3, figsize=(fig_width, fig_height), subplot_kw={'projection':proj})

3. 启用自动布局优化

在创建子图时开启constrained_layout=True,让Matplotlib自动调整子图大小以适配画布尺寸,同时保留投影的正确比例:

fig,axes = plt.subplots(1,3, figsize=(10,10), subplot_kw={'projection':proj}, constrained_layout=True)

内容的提问来源于stack exchange,提问作者Habtie27

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 13:54:56