Plotly Express Choropleth报错:Object of type bytes is not JSON serializable
问题解决:Plotly Choropleth 抛出TypeError: Object of type bytes is not JSON serializable
错误原因
- 字节数据未解析:
files.upload()返回的是键为文件名、值为字节流的字典,直接传给px.choropleth的geojson参数时,字节数据无法被JSON序列化,导致展示图表时出错。 - 参数匹配错误:原代码中
locations参数指定为'Train Station?',这是存储火车站数量的数值列,而非邮编列,无法与GeoJSON中的邮编字段匹配。
修正后的代码
import json from google.colab import files import pandas as pd import plotly.express as px # 上传GeoJSON文件并解析为JSON对象 uploaded = files.upload() filename = next(iter(uploaded.keys())) nj_geo_data = json.loads(uploaded[filename]) # 读取CSV,确保邮编以字符串格式加载 train_df = pd.read_csv("Train Data.csv", converters={'zipcodes': str}) # 创建 choropleth 地图 fig = px.choropleth( train_df, geojson=nj_geo_data, locations='zipcodes', # 对应CSV中的邮编列 featureidkey='properties.ZCTA5CE10', # 对应GeoJSON中的邮编字段 color='Train Station?', # 用火车站数量字段生成颜色映射 projection='mercator' ) # 优化地图显示:自动适配数据范围,隐藏默认底图元素 fig.update_geos(fitbounds="locations", visible=False) fig.show()
关键修正点
- 用
json.loads()将上传的字节数据解析为JSON对象,满足geojson参数的格式要求。 - 修正
locations参数为CSV中的邮编列名(zipcodes),确保与GeoJSON中的properties.ZCTA5CE10字段匹配。 - 添加
color参数绑定火车站数量字段,实现按数值生成颜色渐变的 choropleth 效果。
内容的提问来源于stack exchange,提问作者Tina
相关产品推荐
相关产品推荐

