Plotly Express 美国州级 Choropleth 地图无颜色填充问题排查
问题解决:Plotly Express美国州级Choropleth地图无颜色填充
问题背景
使用美国人口普查局县级人口数据,按州汇总后用Plotly Express绘制Choropleth地图,代码如下:
# 按州汇总人口数据 df = df_raw.groupby('State')['Population'].agg(['count','sum','mean','median','max','min']).reset_index() # 绘制地图 fig = px.choropleth( df, locations='State', color = 'sum', locationmode='USA-states', scope='usa' ) fig.show()
地图可正常渲染、右侧颜色刻度显示正确,但各州形状无颜色填充。
问题原因
当设置locationmode='USA-states'时,Plotly要求locations参数对应的列必须是美国州的两位缩写(如CA、TX),但你的State列存储的是州的全称(如California、Texas),两者无法匹配,导致无法为州填充颜色。
解决方法
方法1:将州全称转换为州缩写
可以使用pandas结合us库(需先安装:pip install us)来转换:
import us # 转换州全称为缩写 df['State'] = df['State'].apply(lambda x: us.states.lookup(x).abbr) # 重新绘制地图 fig = px.choropleth( df, locations='State', color='sum', locationmode='USA-states', scope='usa', title='美国各州人口总数分布' ) fig.show()
方法2:修改locationmode为州全称匹配
如果不想转换缩写,可将locationmode改为'country names',但需要确保州全称与Plotly内置的名称完全一致:
fig = px.choropleth( df, locations='State', color='sum', locationmode='country names', # 改为匹配全称 scope='usa', title='美国各州人口总数分布' ) fig.show()
注意:此方法可能因州全称的拼写/格式差异导致匹配失败,推荐使用方法1。
内容的提问来源于stack exchange,提问作者Andrew Staroscik
相关产品推荐
相关产品推荐

