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

Matplotlib非空间绘图与Geopandas地图并排显示时调整绘图高度匹配地图高度的方法

我懂你这个痛点——明明代码里设置了两列子图,但左边的普通折线图和右边的GeoPandas地图看起来高度不一样,其实核心问题就是两者的坐标轴边框显示、轴范围默认设置不同,导致视觉上的错位。下面给你几个实用的解决办法:

方法1:统一边框样式+同步轴范围(最常用)

GeoPandas绘制地图时,通常会自动隐藏顶部和右侧的坐标轴边框,而普通Matplotlib绘图默认显示全部边框,再加上两者默认的轴范围不同,就会出现视觉高度差。我们可以手动对齐这两个设置:

import numpy as np
import matplotlib.pyplot as plt
import geopandas as gpd
from shapely.geometry import Point

# 生成示例数据(替换成你的真实数据即可)
data = np.arange(10)
gdf = gpd.GeoDataFrame({'geometry': [Point(0,0), Point(1,1)]})

# 创建两列子图,可先设置整体画布尺寸
fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(10, 5))

# 绘制左侧普通图
ax1.plot(data)
# 绘制右侧地图
gdf.plot(ax=ax2)

# 统一边框显示:让左侧子图和地图子图保持一致的边框状态
ax1.spines['top'].set_visible(False)
ax1.spines['right'].set_visible(False)

# 同步y轴范围:强制左侧子图的高度和地图子图完全匹配
y_min, y_max = ax2.get_ylim()
ax1.set_ylim(y_min, y_max)

# 自动调整子图间距,避免拥挤
plt.tight_layout()
plt.show()

方法2:用GridSpec精确控制子图尺寸

如果方法1还达不到你想要的精度,可以用matplotlib.gridspec来更精细地定义子图的布局,确保两者的高度参数完全一致:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
import geopandas as gpd
from shapely.geometry import Point

data = np.arange(10)
gdf = gpd.GeoDataFrame({'geometry': [Point(0,0), Point(1,1)]})

fig = plt.figure(figsize=(10, 5))
# 创建1行2列的网格,两个子图共享高度比例
gs = GridSpec(1, 2, height_ratios=[1], width_ratios=[1, 1])

# 分别添加子图
ax1 = fig.add_subplot(gs[0])
ax2 = fig.add_subplot(gs[1])

ax1.plot(data)
gdf.plot(ax=ax2)

# 同步边框和轴范围
ax1.spines['top'].set_visible(False)
ax1.spines['right'].set_visible(False)
y_min, y_max = ax2.get_ylim()
ax1.set_ylim(y_min, y_max)

plt.tight_layout()
plt.show()

方法3:手动设置子图位置(终极方案)

如果前两种方法都没解决问题,你可以直接获取右侧地图子图的位置参数,强制左侧子图和它对齐:

import numpy as np
import matplotlib.pyplot as plt
import geopandas as gpd
from shapely.geometry import Point

data = np.arange(10)
gdf = gpd.GeoDataFrame({'geometry': [Point(0,0), Point(1,1)]})

fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(10, 5))

ax1.plot(data)
gdf.plot(ax=ax2)

# 获取右侧地图子图的位置信息(left, bottom, width, height)
pos2 = ax2.get_position()
# 手动设置左侧子图的位置:高度、垂直起点和右侧完全一致,只调整水平位置
ax1.set_position([pos2.x0 - pos2.width*1.1, pos2.y0, pos2.width, pos2.height])

plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 06:32:33