小编典典

Plotly Choropleth贴图的下拉菜单

python

我正在尝试创建Choropleth贴图。下面是一个有效的示例:

df = px.data.gapminder().query("year==2007")

fig = go.Figure(data=go.Choropleth(
    locations=happy['iso'], # Spatial coordinates
    z = happy['Happiness'].astype(float), # Data to be color-coded
    colorbar_title = "Happiness Score",
))

fig.update_layout(
    title_text = 'Life Expectancy in 2007'
)

fig.show()

但是,我想创建一个下拉菜单,该菜单将更改不同变量(例如,预期寿命,GDP,人口)之间的绘制值。我相信这是可能的,但尚未在线上看到任何教程。他们中的大多数只使用其他类型的条形图或散点图。

到目前为止,这是我得到的:

# Initialize figure
fig = go.Figure()

# Add Traces
fig.add_trace(go.Figure(data=go.Choropleth(
    locations=df['iso_alpha'], # Spatial coordinates
    z = df['lifeExp'].astype(float), # Data to be color-coded
    colorbar_title = "Life Expectancy")))

fig.add_trace(go.Figure(data=go.Choropleth(
    locations=df['iso_alpha'], # Spatial coordinates
    z = df['gdpPercap'].astype(float), # Data to be color-coded
    colorbar_title = "GDP per capita")))

但是我不确定如何从这里继续。我是否需要通过fig.update_layout或其他方式更新图形的布局?


阅读 314

收藏
2021-01-20

共1个答案

小编典典

有两种解决方法

短跑

# save this as app.py
import pandas as pd
import plotly.graph_objs as go
import plotly.express as px
import dash
import dash_core_components as dcc
import dash_html_components as html

# Data
df = 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-coded
        colorbar_title=value))
    fig.update_layout(title=f"<b>{value}</b>", title_x=0.5)
    return fig

if __name__ == '__main__':
    app.run_server()

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

密谋

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

import pandas as pd
import numpy as np
import plotly.graph_objs as go
import plotly.express as px

# Data
df = 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 visible
visible = np.array(cols_dd)

# define traces and buttons at once
traces = []
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-coded
        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 figure
fig = go.Figure(data=traces,
                layout=dict(updatemenus=updatemenus))
# This is in order to get the first title displayed correctly
first_title = cols_dd[0]
fig.update_layout(title=f"<b>{first_title}</b>",title_x=0.5)
fig.show()
2021-01-20