There are two ways to solve this
Dash
# 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()
run this as python app.py
and go to http://127.0.0.1:8050
Plotly
In this case we need to play with visibility of different traces and create buttons in a way they show one traces and hide all the others.
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()
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…