簡體   English   中英

如何使用 plotly 下拉菜單功能更新我的等值線 map 中的 z 值?

[英]How can I use the plotly dropdown menu feature to update the z value in my choropleth map?

我只想在 plot 上創建一個菜單,我只能在其中更改數據中的 z 值。 我嘗試查看此處的其他示例: https://plot.ly/python/dropdowns/#restyle-dropdown但很難,因為這些示例與我的 plot 並不完全相似。

import plotly
import plotly.plotly as py
import plotly.graph_objs as go
import pandas as pd

df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_world_gdp_with_codes.csv')

data = [go.Choropleth(
    locations = df['CODE'],
    z = df['GDP (BILLIONS)'],
    text = df['COUNTRY'],
    colorscale = [
        [0, "rgb(5, 10, 172)"],
        [0.35, "rgb(40, 60, 190)"],
        [0.5, "rgb(70, 100, 245)"],
        [0.6, "rgb(90, 120, 245)"],
        [0.7, "rgb(106, 137, 247)"],
        [1, "rgb(220, 220, 220)"]
    ],
    autocolorscale = False,
    reversescale = True,
    marker = go.choropleth.Marker(
        line = go.choropleth.marker.Line(
            color = 'rgb(180,180,180)',
            width = 0.5
        )),
    colorbar = go.choropleth.ColorBar(
        tickprefix = '$',
        title = 'GDP<br>Billions US$'),
)]

layout = go.Layout(
    title = go.layout.Title(
        text = '2014 Global GDP'
    ),
    geo = go.layout.Geo(
        showframe = False,
        showcoastlines = False,
        projection = go.layout.geo.Projection(
            type = 'equirectangular'
        )
    ),
    annotations = [go.layout.Annotation(
        x = 0.55,
        y = 0.1,
        xref = 'paper',
        yref = 'paper',
        text = 'Source: <a href="https://www.cia.gov/library/publications/the-world-factbook/fields/2195.html">\
            CIA World Factbook</a>',
        showarrow = False
    )]
)

fig = go.Figure(data = data, layout = layout)
py.iplot(fig, filename = 'd3-world-map')

自問這個問題以來已經有一段時間了,但我認為它仍然值得回答。 我無法說出自 2019 年提出這個問題以來可能發生了怎樣的變化,但這在今天是有效的。

在此處輸入圖像描述 在此處輸入圖像描述

在此處輸入圖像描述 在此處輸入圖像描述

首先,我將提供用於創建新z值和下拉菜單的代碼,然后我將提供用於在一個塊中創建這些圖形的所有代碼(更容易剪切和粘貼......以及所有那)。

這是我在z字段中用於備用數據的數據。

import plotly.graph_objects as go
import pandas as pd
import random

z2 = df['GDP (BILLIONS)'] * .667 + 12
random.seed(21)
random.shuffle(z2)
df['z2'] = z2                        # example as another column in df
print(df.head()) # validate as expected

z3 = df['GDP (BILLIONS)'] * .2 + 1000
random.seed(231)
random.shuffle(z3)                   # example as a series outside of df

z4 = df['GDP (BILLIONS)']**(1/3) * df['GDP (BILLIONS)']**(1/2)
random.seed(23)
random.shuffle(z4)
z4 = z4.tolist()                     # example as a basic Python list

要添加按鈕以更改z ,您需要將updatemenus添加到您的布局。 每個dict()都是一個單獨的下拉選項。 至少,每個按鈕都需要一個method 、一個labelargs 這些表示正在更改的內容(數據method 、布局或兩者)、下拉列表中的名稱( label )以及新信息(本例中為新的z )。

數據更改的args (其中方法是restyleupdate )還可以包括應用更改的跟蹤。 因此,如果您有一個條形圖和一個折線圖,您可能會有一個僅更改條形圖的按鈕。

使用與您相同的結構:

updatemenus = [go.layout.Updatemenu(
    x = 1, xanchor = 'right', y = 1.15, type = "dropdown", 
    pad = {'t': 5, 'r': 20, 'b': 5, 'l': 30}, # around all buttons (not indiv buttons)
    buttons = list([
        dict(
            args = [{'z': [df['GDP (BILLIONS)']]}], # original data; nest data in []
            label = 'Return to the Original z',
            method = 'restyle'                  # restyle is for trace updates
        ),
        dict(
            args = [{'z': [df['z2']]}],         # nest data in []
            label = 'A different z',
            method = 'restyle'
        ),
        dict(
            args = [{'z': [z3]}],               # nest data in []
            label = 'How about this z?',
            method = 'restyle'
        ),
        dict(
            args = [{'z': [z4]}],               # nest data in []
            label = 'Last option for z',
            method = 'restyle'
        )])
)]

用於在一個塊中創建此圖的所有代碼(包括上面顯示的代碼)。

import plotly.graph_objs as go
import pandas as pd
import ssl 
import random

# to collect data without an error
ssl._create_default_https_context = ssl._create_unverified_context

# data used in plot
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_world_gdp_with_codes.csv')

# z values used in buttons
z2 = df['GDP (BILLIONS)'] * .667 + 12
random.seed(21)
random.shuffle(z2)
df['z2'] = z2                       # example as another column in the data frame
print(df.head()) # validate as expected

z3 = df['GDP (BILLIONS)'] * .2 + 1000
random.seed(231)
random.shuffle(z3)                  # example as a series outside of the data frame

z4 = df['GDP (BILLIONS)']**(1/3) * df['GDP (BILLIONS)']**(1/2)
random.seed(23)
random.shuffle(z4)
z4 = z4.tolist()                    # example as a basic Python list

data = [go.Choropleth(
    locations = df['CODE'], z = df['GDP (BILLIONS)'], text = df['COUNTRY'],
    colorscale = [
        [0, "rgb(5, 10, 172)"],
        [0.35, "rgb(40, 60, 190)"],
        [0.5, "rgb(70, 100, 245)"],
        [0.6, "rgb(90, 120, 245)"],
        [0.7, "rgb(106, 137, 247)"],
        [1, "rgb(220, 220, 220)"]],
    reversescale = True,
    marker = go.choropleth.Marker(
        line = go.choropleth.marker.Line(
            color = 'rgb(180,180,180)', width = 0.5)),
    colorbar = go.choropleth.ColorBar(
        tickprefix = '$',
        title = 'GDP<br>Billions US$',
        len = .6)                           # I added this for aesthetics
)]

layout = go.Layout(
    title = go.layout.Title(text = '2014 Global GDP'),
    geo = go.layout.Geo(
        showframe = False, showcoastlines = False,
        projection = go.layout.geo.Projection(
            type = 'equirectangular')
    ),
    annotations = [go.layout.Annotation(
        x = 0.55, y = 0.1, xref = 'paper', yref = 'paper',
        text = 'Source: <a href="https://www.cia.gov/library/publications/the-world-factbook/fields/2195.html">\
            CIA World Factbook</a>',
        showarrow = False
    )],
    updatemenus = [go.layout.Updatemenu(
        x = 1, xanchor = 'right', y = 1.15, type = "dropdown",
        pad = {'t': 5, 'r': 20, 'b': 5, 'l': 30},
        buttons = list([
            dict(
                args = [{'z': [df['GDP (BILLIONS)']]}], # original data; nest data in []
                label = 'Return to the Original z',
                method = 'restyle'                  # restyle is for trace updates only
            ),
            dict(
                args = [{'z': [df['z2']]}],         # nest data in []
                label = 'A different z',
                method = 'restyle'
            ),
            dict(
                args = [{'z': [z3]}],               # nest data in []
                label = 'How about this z?',
                method = 'restyle'
            ),
            dict(
                args = [{'z': [z4]}],               # nest data in []
                label = 'Last option for z',
                method = 'restyle'
            )])
    )]
)

fig = go.Figure(data = data, layout = layout)
fig.show()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM