Plotly Choropleth Map Plots 的下拉菜单 [英] Dropdown menu for Plotly Choropleth Map Plots

查看:32
本文介绍了Plotly Choropleth Map Plots 的下拉菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建区域分布图.下面是一个有效的例子:

I am trying to create choropleth maps. Below is an example that works:

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、人口)之间的绘图值.我相信这是可能的,但还没有在网上看到任何教程.他们中的大多数只是使用其他类型的条形图或散点图.

However, I would like to create a dropdown menu that will change the plotted values between different variables (e.g., Life Expectancy, GDP, Population). I believe that this is possible but have not seen any tutorial online. Most of them just uses other kind of barcharts or scatterplots.

这是我目前得到的:

# 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 之类的方式更新图形的布局?

But I am not sure how to proceed from here. Do I need to update the layout of the figure via fig.update_layout or something?

推荐答案

有两种方法可以解决这个问题

There are two ways to solve this

# 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

run this as python app.py and go to http://127.0.0.1:8050

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

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()

这篇关于Plotly Choropleth Map Plots 的下拉菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆