如何绘制邮政编码级别的Choropleth地图?解决渲染空白问题
邮政编码级Choropleth地图绘制问题解决
问题背景
我有如下结构的Pandas DataFrame df:
user_id zip_code city county state 0001 10021 New York New York NY 0002 10003 New York New York NY 0003 06831 Greenwich Fairfield CT 0004 33172 Miami Miami-Dade FL 0005 07417 Franklin Lakes Bergen NJ
尝试用以下代码绘制邮政编码级的Choropleth地图,但渲染出空白:
from urllib.request import urlopen import json import requests with urlopen('https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json') as response: counties = json.load(response) fig = px.choropleth(df, geojson= counties, locations='fips', locationmode="USA-states", scope="usa", color='user_id', color_continuous_scale="blues", ) fig.show()
请问如何正确绘制邮政编码级的Choropleth地图?
核心问题与修正方案
你的代码存在三个关键错误,直接导致地图空白:
GeoJSON数据源错误
你加载的是县级别GeoJSON(基于FIPS编码),但绘制邮政编码级地图需要匹配ZIP Code的地理边界数据。locations参数不匹配
代码中指定locations='fips',但你的DataFrame中并没有fips列,应该使用存在的zip_code列。locationmode参数错误
设置为"USA-states"是州级别的匹配模式,邮政编码需要使用"USA-zip-code"模式。
修正后的完整代码
import pandas as pd import plotly.express as px # 初始化示例DataFrame(如果你的df已存在可跳过这部分) df = pd.DataFrame({ 'user_id': ['0001', '0002', '0003', '0004', '0005'], 'zip_code': ['10021', '10003', '06831', '33172', '07417'], 'city': ['New York', 'New York', 'Greenwich', 'Miami', 'Franklin Lakes'], 'county': ['New York', 'New York', 'Fairfield', 'Miami-Dade', 'Bergen'], 'state': ['NY', 'NY', 'CT', 'FL', 'NJ'] }) # 绘制邮政编码级Choropleth地图 fig = px.choropleth( df, locations='zip_code', # 匹配DataFrame中的邮政编码列 locationmode="USA-zip-code", # 指定邮政编码匹配模式 scope="usa", # 限定地图范围为美国 color='user_id', # 按user_id着色(若需统计数量可先分组聚合) color_continuous_scale="blues", hover_data=['city', 'county', 'state'] # 鼠标悬停显示额外信息 ) fig.update_layout(title_text='美国邮政编码级用户分布地图') fig.show()
额外提示
- 如果需要自定义ZIP Code地理数据,确保GeoJSON中的编码与你的
zip_code列格式完全一致(比如5位字符串,无多余字符)。 - 若要展示每个邮政编码的用户数量,先对数据做分组统计:
zip_counts = df.groupby('zip_code')['user_id'].count().reset_index(name='user_count') # 再用zip_counts作为数据源绘图,color参数改为'user_count'
内容的提问来源于stack exchange,提问作者zeroes_ones
相关产品推荐
相关产品推荐

