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

如何在Cartopy中修改图形宽高?figsize仅改变空白区域

调整Cartopy地图实际宽高的解决办法

嘿,我懂你遇到的困扰——设置plt.figure的figsize参数时,只会改变图形周围的空白,地图本身的宽高比例却纹丝不动对吧?这其实是因为Cartopy为了保证地图投影的正确性,会自动约束轴(Axes)的宽高比,默认是'equal'模式,所以单纯调figsize只会留白。下面给你几个实用的解决思路:

方法一:根据地图区域比例匹配figsize

这是最稳妥的方式,先算出你要展示的地理区域的宽高比,再让figure的尺寸匹配这个比例,这样地图就能刚好填满figure,不会有多余空白,还能保证地图比例正确。

示例代码:

import cartopy.crs as ccrs
import cartopy.feature as cfeature
import matplotlib.pyplot as plt

def main():
    # 定义目标地理范围
    x_min, x_max = -20, 60
    y_min, y_max = -40, 45
    # 计算区域的宽高比
    region_aspect = (x_max - x_min) / (y_max - y_min)
    
    # 根据比例设置figsize,这里把高度设为10,宽度按比例计算
    fig = plt.figure(figsize=(10 * region_aspect, 10))
    ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree())
    
    ax.set_extent([x_min, x_max, y_min, y_max], crs=ccrs.PlateCarree())
    ax.add_feature(cfeature.LAND)
    ax.add_feature(cfeature.OCEAN)
    ax.add_feature(cfeature.COASTLINE)
    ax.add_feature(cfeature.BORDERS, linestyle=':')
    ax.add_feature(cfeature.LAKES, alpha=0.5)
    ax.add_feature(cfeature.RIVERS)
    
    plt.show()

if __name__ == '__main__':
    main()

方法二:开启自动布局减少空白

如果不想计算比例,可以开启matplotlib的自动布局功能,让它自动调整轴的大小和位置,尽量填满figure空间。

示例代码:

import cartopy.crs as ccrs
import cartopy.feature as cfeature
import matplotlib.pyplot as plt

def main():
    # 开启constrained_layout自动调整布局
    fig = plt.figure(figsize=(10, 6), constrained_layout=True)
    ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree())
    
    ax.set_extent([-20, 60, -40, 45], crs=ccrs.PlateCarree())
    ax.add_feature(cfeature.LAND)
    ax.add_feature(cfeature.OCEAN)
    ax.add_feature(cfeature.COASTLINE)
    ax.add_feature(cfeature.BORDERS, linestyle=':')
    ax.add_feature(cfeature.LAKES, alpha=0.5)
    ax.add_feature(cfeature.RIVERS)
    
    plt.show()

if __name__ == '__main__':
    main()

你可以直接调整figsize的数值来控制整体图形的大小,自动布局会帮你把地图尽量填满figure。

方法三:手动设置轴的位置和大小

如果上面两种方法都不符合你的需求,还可以直接手动指定轴的位置和尺寸,完全自定义地图的大小。

示例代码:

import cartopy.crs as ccrs
import cartopy.feature as cfeature
import matplotlib.pyplot as plt

def main():
    fig = plt.figure(figsize=(10, 10))
    ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree())
    
    ax.set_extent([-20, 60, -40, 45], crs=ccrs.PlateCarree())
    ax.add_feature(cfeature.LAND)
    ax.add_feature(cfeature.OCEAN)
    ax.add_feature(cfeature.COASTLINE)
    ax.add_feature(cfeature.BORDERS, linestyle=':')
    ax.add_feature(cfeature.LAKES, alpha=0.5)
    ax.add_feature(cfeature.RIVERS)
    
    # 手动设置轴的位置:[左边界, 下边界, 宽度, 高度],数值范围是0-1(相对于figure的比例)
    ax.set_position([0.05, 0.05, 0.9, 0.8])
    plt.show()

if __name__ == '__main__':
    main()

调整set_position里的四个参数,就能精确控制地图在figure里的大小和位置啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:21:55