Plotly choropleth仅显示部分西班牙市镇地图及背景色修改问题求助
问题1:部分市镇无填充色但悬停可显示数据
核心原因
你当前遇到的填充缺失问题主要由两个常见原因导致:
- Plotly的
px.choropleth接口的geojson参数要求接收GeoJSON格式的字典对象,直接传入文件路径会存在解析异常,导致部分几何的填充渲染失败 - 你使用的GADM 3.6版本西班牙市镇级GeoJSON的多边形缠绕顺序不符合Plotly的渲染规则,部分外环被识别为内部空洞,因此不会渲染填充色,但几何要素本身正常存在,所以悬停时可以正常触发数据显示。
解决步骤
- 第一步:先将GeoJSON文件手动加载为字典对象再传入接口,代码如下:
import json import pandas as pd import plotly.express as px df = pd.read_csv("result.csv",sep=";") # 手动加载GeoJSON文件 with open("data\\gadm36_ESP_4.json", "r", encoding="utf-8") as f: esp_geojson = json.load(f) fig=px.choropleth(df, geojson=esp_geojson, featureidkey='properties.NAME_4', locations='CityName', color='Value', color_continuous_scale='sunset', title='Expected Output' , height=700 ) fig.update_geos(fitbounds="locations", visible=True) fig.show()
- 第二步:如果上述操作后仍存在填充缺失,使用geopandas修正多边形缠绕顺序:
import json import geopandas as gpd from shapely.ops import orient import pandas as pd import plotly.express as px df = pd.read_csv("result.csv",sep=";") # 读取GeoJSON并修正缠绕顺序 gdf = gpd.read_file("data\\gadm36_ESP_4.json") gdf["geometry"] = gdf["geometry"].apply(lambda x: orient(x, sign=1.0)) # 转回Plotly可用的GeoJSON字典 esp_geojson = json.loads(gdf.to_json()) # 后续绘图代码和上述一致 fig=px.choropleth(df, geojson=esp_geojson, featureidkey='properties.NAME_4', locations='CityName', color='Value', color_continuous_scale='sunset', title='Expected Output' , height=700 ) fig.update_geos(fitbounds="locations", visible=True) fig.show()
问题2:自定义地图背景色不生效
核心原因
你之前设置visible=True会加载Plotly默认的底图图层,该图层默认是白色,会覆盖你设置的bgcolor,所以自定义背景色不生效。
解决代码
修改update_geos参数,关闭默认底图后再设置背景色即可生效:
fig.update_geos( fitbounds="locations", visible=False, # 关闭默认底图 bgcolor='rgba(173,157,157,1)' # 自定义背景色 )
如果需要保留底图的国界、省界线等要素,可以单独开启对应配置:
fig.update_geos( fitbounds="locations", visible=False, bgcolor='rgba(173,157,157,1)', showcountries=True, countrycolor="white", # 显示国界 showregions=True, regioncolor="white" # 显示省界 )
内容的提问来源于stack exchange,提问作者DaveA
相关产品推荐
相关产品推荐

