Plotly Express Choropleth地图无输出问题求助
无法生成Plotly Choropleth地图的排查与修复方案
核心问题排查点
1. 渲染器配置错误
- Google Colab环境下,设置
pio.renderers.default = 'browser'会导致无法在笔记本内显示,必须改为colab渲染器; - 本地VS Code环境建议使用
vscode或notebook渲染器,确保编辑器支持Plotly可视化渲染。
2. GeoJSON与CSV的ID匹配问题
Plotly需要CSV的locations字段与GeoJSON中区域的标识字段完全对应,否则无法关联数据:
- 先打印GeoJSON的属性字段,确认匹配键:
print([feature['properties'] for feature in x['features'][:2]]) - 再打印CSV的
id列,检查值是否匹配:print(y['id'].head()) - 如果不匹配,在
px.choropleth中添加featureidkey参数指定GeoJSON中的对应字段,例如GeoJSON用properties.DISTRICT作为区域标识:fig = px.choropleth( y, locations="id", geojson=x, color="Females", featureidkey="properties.DISTRICT" # 替换为实际匹配的属性键 )
3. 文件加载路径问题
- 本地运行:确保
odisha_disticts.geojson和data.csv与代码文件在同一目录,或使用绝对路径; - Colab环境:需先上传文件或挂载Google Drive,挂载示例代码:
from google.colab import drive drive.mount('/content/drive') # 替换为Drive中的实际文件路径 x = json.load(open("/content/drive/MyDrive/你的文件夹/odisha_disticts.geojson","r")) y = pd.read_csv("/content/drive/MyDrive/你的文件夹/data.csv")
4. 数据格式验证
检查CSV中id和Females字段是否存在缺失值或格式错误:
print(y.info()) print(y.isnull().sum())
修改后的可运行代码示例
Colab版本
import json import pandas as pd import plotly.express as px import plotly.io as pio from google.colab import drive # 挂载Google Drive drive.mount('/content/drive') # 配置Colab渲染器 pio.renderers.default = 'colab' # 加载文件(替换为你的实际路径) x = json.load(open("/content/drive/MyDrive/你的文件夹/odisha_disticts.geojson","r")) y = pd.read_csv("/content/drive/MyDrive/你的文件夹/data.csv") y.drop("Unnamed: 0", axis='columns', inplace=True) # 验证ID匹配 print("GeoJSON属性示例:", [f['properties'] for f in x['features'][:1]]) print("CSV ID示例:", y['id'].head()) # 创建Choropleth地图 fig = px.choropleth( y, locations="id", geojson=x, color="Females", featureidkey="properties.DISTRICT" # 替换为实际匹配的属性键 ) fig.update_geos(fitbounds="locations", visible=False) fig.show()
本地VS Code版本
import json import pandas as pd import plotly.express as px import plotly.io as pio # 配置VS Code渲染器 pio.renderers.default = 'vscode' # 加载文件(确保文件在当前目录) x = json.load(open("odisha_disticts.geojson","r")) y = pd.read_csv("data.csv") y.drop("Unnamed: 0", axis='columns', inplace=True) # 验证ID匹配 print("GeoJSON属性示例:", [f['properties'] for f in x['features'][:1]]) print("CSV ID示例:", y['id'].head()) # 创建Choropleth地图 fig = px.choropleth( y, locations="id", geojson=x, color="Females", featureidkey="properties.DISTRICT" # 替换为实际匹配的属性键 ) fig.update_geos(fitbounds="locations", visible=False) fig.show()
内容的提问来源于stack exchange,提问作者vivek
相关产品推荐
相关产品推荐

