Plotly Express Choropleth地图颜色方案下拉切换问题求助
问题解决:通过下拉按钮切换Plotly Choropleth Mapbox的颜色刻度
问题原因
你当前代码里的updatemenus按钮参数写法错误:
- 使用
update方法时,args的第一个元素必须是字典形式,用来指定要更新的图表属性,而非直接传键值对 range_color是Plotly Express的初始化参数,在更新时需要对应到trace的zmin和zmax属性,而非直接用range_color
修正方案
将每个按钮的args调整为字典格式,明确指定要更新的trace属性:
- 切换颜色刻度时,更新
colorscale属性 - 调整颜色范围时,更新
zmin和zmax属性
修改后的完整代码
from urllib.request import urlopen import json with urlopen('https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json') as response: counties = json.load(response) import pandas as pd df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/fips-unemp-16.csv", dtype={"fips": str}) import plotly.express as px fig = px.choropleth_mapbox(df, geojson=counties, locations='fips', color='unemp', color_continuous_scale="ylgn", range_color=(0, 12), mapbox_style="carto-positron", zoom=3, center = {"lat": 37.0902, "lon": -95.7129}, opacity=0.5, labels={'unemp':'unemployment rate'} ) fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0}) fig.update_layout( updatemenus=[ dict( active=0, buttons=list([ dict(label="ylgn", method="update", args=[{"colorscale": "ylgn"}, {}]), dict(label="temps", method="update", args=[{"colorscale": "temps"}, {}]), dict(label="范围0-500", method="update", args=[{"zmin": 0, "zmax": 500}, {}]), dict(label="范围0-12", method="update", args=[{"zmin": 0, "zmax": 12}, {}]), ]), ) ]) # 设置标题 fig.update_layout(title_text="美国失业率地图") fig.show()
关键说明
- 所有内置颜色刻度名称(如
viridis、gray、haline等)都可以直接替换到colorscale的值中 args的第二个空字典{}用来保留布局设置,避免更新时覆盖现有布局- 颜色范围的更新通过
zmin和zmax实现,对应初始化时的range_color参数
内容的提问来源于stack exchange,提问作者SKbeats
相关产品推荐
相关产品推荐

