Plotly Choropleth贴图的下拉菜单

Plotly Choropleth贴图的下拉菜单,第1张

Plotly Choropleth贴图的下拉菜单

有两种解决方法

短跑
# save this as app.pyimport pandas as pdimport plotly.graph_objs as goimport plotly.express as pximport dashimport dash_core_components as dccimport dash_html_components as html# Datadf = px.data.gapminder().query("year==2007")df = df.rename(columns=dict(pop="Population",      gdpPercap="GDP per Capita",      lifeExp="Life Expectancy"))cols_dd = ["Population", "GDP per Capita", "Life Expectancy"]app = dash.Dash()app.layout = html.Div([    dcc.Dropdown(        id='demo-dropdown',        options=[{'label': k, 'value': k} for k in cols_dd],        value=cols_dd[0]    ),    html.Hr(),    dcc.Graph(id='display-selected-values'),])@app.callback(    dash.dependencies.Output('display-selected-values', 'figure'),    [dash.dependencies.Input('demo-dropdown', 'value')])def update_output(value):    fig = go.Figure()    fig.add_trace(go.Choropleth(       locations=df['iso_alpha'], # Spatial coordinates        z=df[value].astype(float), # Data to be color-pred        colorbar_title=value))    fig.update_layout(title=f"<b>{value}</b>", title_x=0.5)    return figif __name__ == '__main__':    app.run_server()

运行它

python app.py
并转到http://127.0.0.1:8050

密谋

在这种情况下,我们需要处理不同迹线的可见性,并以显示一条迹线并隐藏所有其他迹线的方式创建按钮。

import pandas as pdimport numpy as npimport plotly.graph_objs as goimport plotly.express as px# Datadf = px.data.gapminder().query("year==2007")df = df.rename(columns=dict(pop="Population",      gdpPercap="GDP per Capita",      lifeExp="Life Expectancy"))cols_dd = ["Population", "GDP per Capita", "Life Expectancy"]# we need to add this to select which trace # is going to be visiblevisible = np.array(cols_dd)# define traces and buttons at oncetraces = []buttons = []for value in cols_dd:    traces.append(go.Choropleth(       locations=df['iso_alpha'], # Spatial coordinates        z=df[value].astype(float), # Data to be color-pred        colorbar_title=value,        visible= True if value==cols_dd[0] else False))    buttons.append(dict(label=value,  method="update",  args=[{"visible":list(visible==value)},        {"title":f"<b>{value}</b>"}]))updatemenus = [{"active":0,     "buttons":buttons,    }]# Show figurefig = go.Figure(data=traces,     layout=dict(updatemenus=updatemenus))# This is in order to get the first title displayed correctlyfirst_title = cols_dd[0]fig.update_layout(title=f"<b>{first_title}</b>",title_x=0.5)fig.show()


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/4911771.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-12
下一篇 2022-11-12

发表评论

登录后才能评论

评论列表(0条)

保存