hvPlot+Carto底图叠加GeoPandas时MultiPolygons验证失败
数据小陈
ValueError: failed to validate MultiPolygons(...).hatch_color ... got dim('norm_occurrences') 通常不是 CARTO 底图或 GeoPandas 数据损坏导致的。更可能的情况是:hvPlot/HoloViews 把 GeoDataFrame 的 c='norm_occurrences' 颜色维度与 tiles=carto_tiles 一起使用时,颜色维度被传给了 MultiPolygons 的 hatch_color 样式项,而 hatch_color 不接受 dim(...) 表达式,于是验证失败。优先改用显式 color=,并手动叠加 CARTO Tiles;如果几何列里混有 Polygon 和 MultiPolygon,再统一几何类型。
原因
c=是 hvPlot 的颜色简写。在某些geo=True + tiles=的组合里,颜色维度可能被传到hatch_color。hatch_color只接受颜色、字符串、字段等有限类型,不接受dim('norm_occurrences')。- CARTO 底图是瓦片图层,hvPlot 的
tiles=参数会参与叠加。手动用hv.Tiles与多边形图层做*叠加,可以绕开这段参数传递逻辑。 - GeoDataFrame 同时存在
Polygon和MultiPolygon时,hvPlot 更容易落到MultiPolygons元素上,触发样式验证问题。统一几何类型能减少这种不确定性。
解决步骤
- 先检查几何类型:
print(occurrence_gdf.geom_type.value_counts())
- 如果混有
Polygon和MultiPolygon,统一成MultiPolygon(或至少统一成同一种类型):
from shapely.geometry import Polygon, MultiPolygon
def to_multipolygon(geom):
if geom is None:
return None
if isinstance(geom, Polygon):
return MultiPolygon([geom])
return geom
occurrence_gdf = occurrence_gdf.copy()
occurrence_gdf['geometry'] = occurrence_gdf['geometry'].apply(to_multipolygon)
- 把
c=改成color=,同时不要直接把tiles=carto_tiles传给 hvPlot,改为手动叠加:
import calendar
import panel as pn
import holoviews as hv
import hvplot.pandas # noqa
import cartopy.crs as ccrs
xmin, ymin, xmax, ymax = occurrence_gdf.total_bounds
slider = pn.widgets.DiscreteSlider(
name='month',
options={calendar.month_name[i]: i for i in range(1, 13)}
)
carto_tiles = hv.Tiles(
'https://basemaps.cartocdn.com/rastertiles/voyager/{Z}/{X}/{Y}.png'
'?key=cb1_446c_1_8946b413de0ace50f732dbf1',
name='CARTO'
).opts(crs=ccrs.GOOGLE_MERCATOR)
occurrence_plot = occurrence_gdf.hvplot(
color='norm_occurrences', # 关键:显式 color
groupby='month',
geo=True,
crs=ccrs.GOOGLE_MERCATOR, # CARTO 是 Web Mercator,偏移时优先用这个
title='Least Sandpiper Migration Based on Normalized Mean Number of Monthly Observations',
xlim=(xmin, xmax),
ylim=(ymin, ymax),
frame_height=600,
frame_width=900,
widget_location='bottom',
colorbar=True,
clabel='Normalized Mean Number of Observations',
clim=(0, 0.014565),
widgets={'month': slider},
)
migration_plot = carto_tiles * occurrence_plot
interactive_migration_plot = pn.panel(migration_plot)
interactive_migration_plot
- 如果仍然报同类验证错误,可以显式关闭 hatch 样式再试:
occurrence_plot = occurrence_gdf.hvplot(
color='norm_occurrences',
hatch_color=None,
groupby='month',
geo=True,
crs=ccrs.GOOGLE_MERCATOR,
# 其他参数同上
)
注意事项
ccrs.Mercator()不一定等同于 CARTO 使用的 Web Mercator。底图出现偏移时,优先用ccrs.GOOGLE_MERCATOR或ccrs.Mercator.GOOGLE。- 手动叠加时顺序是
carto_tiles * occurrence_plot,Tiles 在前作为底层;顺序反过来会盖住多边形。 - 如果使用
groupby='month'后仍然报错,可以先把groupby去掉生成单帧图,确认问题来自颜色维度还是几何类型。 - 可以先把
hvplot、holoviews、panel升级到当前稳定版再试。这类样式验证问题有时会在新版本中调整,但不要依赖未验证的版本号。 - 数据量很大时,交互地图可能较慢,可以先用
occurrence_gdf.sample(...)做小样本排查。
备注:内容仅供参考。
