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

使用Geopandas的missing_kwds导致地图形状改变,求解决方案

解决Geopandas 0.11.1中missing_kwds导致地图形状偏移的问题

问题描述

在Geopandas 0.11.1版本中,使用plot方法的missing_kwds参数为含NaN值的地理要素设置特定颜色时,会出现地图形状轻微偏移的问题,快速切换视图时该偏移现象更为明显。

复现代码

不使用missing_kwds的地图代码

import geopandas
import matplotlib.pyplot as plt
df = geopandas.read_file(geopandas.datasets.get_path("naturalearth_lowres"))
df.plot()
plt.savefig('world1.png')

使用missing_kwds的地图代码

import geopandas
import matplotlib.pyplot as plt
import numpy as np
df = geopandas.read_file(geopandas.datasets.get_path("naturalearth_lowres"))
df.loc[df.name=="China", 'pop_est'] = np.nan
df.plot(column="pop_est", missing_kwds=dict(color="lightgray"))
plt.savefig('world2.png')

解决方案

方案1:手动分离图层绘制

通过将含有效数据的要素与含NaN值的要素分离,分别调用plot方法绘制,避免missing_kwds导致的形状偏移问题:

import geopandas
import matplotlib.pyplot as plt
import numpy as np

df = geopandas.read_file(geopandas.datasets.get_path("naturalearth_lowres"))
df.loc[df.name=="China", 'pop_est'] = np.nan

# 拆分数据集为有效数据和缺失数据
df_valid = df.dropna(subset=["pop_est"])
df_missing = df[df["pop_est"].isna()]

# 创建画布并依次绘制图层
fig, ax = plt.subplots()
df_valid.plot(column="pop_est", ax=ax)
df_missing.plot(color="lightgray", ax=ax)

plt.savefig('world_fixed.png')

方案2:升级Geopandas版本

该问题是Geopandas 0.11.x版本的已知bug,在0.12.0及以上版本中已被修复。升级到最新稳定版即可直接使用missing_kwds参数而无形状偏移问题:

pip install --upgrade geopandas

内容的提问来源于stack exchange,提问作者mikael-s

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 02:10:21