在plotly python中将时间滑块与下拉菜单组合

问题描述 投票:0回答:1

我正在尝试创建一个带有时间滑块的分区统计图来选择日期。我现在还想添加一个下拉菜单来选择要显示数据的数据集。这是一个最小的例子:

import plotly.graph_objects as go
import pandas as pd

data_2019 = pd.DataFrame({
    'year': 2019,
    'region': ['Germany', 'Denmark', 'Japan', 'France', 'Italy', 'Spain', 'Canada', 'Brazil', 'India', 'Australia',
               'China', 'Russia', 'South Korea', 'Netherlands', 'Sweden', 'Norway', 'Finland', 'Mexico',
               'Argentina', 'Chile',
               'Germany', 'Denmark', 'Japan', 'France', 'Italy', 'Spain', 'Canada', 'Brazil', 'India', 'Australia'],
    'date': ['01-01', '01-01', '01-01', '02-01', '02-01', '02-01', '03-01', '03-01', '03-01', '04-01',
             '04-01', '04-01', '05-01', '05-01', '05-01', '06-01', '06-01', '06-01', '07-01', '07-01',
             '08-01', '08-01', '08-01', '09-01', '09-01', '09-01', '10-01', '10-01', '10-01', '11-01'],
    'valence': [0.3, 0.25, 0.22, 0.21, 0.18, 0.15, 0.1, 0.12, 0.14, 0.15,
                0.17, 0.19, 0.21, 0.23, 0.25, 0.27, 0.29, 0.31, 0.33, 0.35,
                0.37, 0.39, 0.41, 0.43, 0.45, 0.47, 0.49, 0.51, 0.53, 0.55]
})

data_2020 = pd.DataFrame({
    'year': 2020,
    'region': ['Germany', 'Denmark', 'Japan', 'France', 'Italy', 'Spain', 'Canada', 'Brazil', 'India', 'Australia',
               'China', 'Russia', 'South Korea', 'Netherlands', 'Sweden', 'Norway', 'Finland', 'Mexico',
               'Argentina', 'Chile',
               'Germany', 'Denmark', 'Japan', 'France', 'Italy', 'Spain', 'Canada', 'Brazil', 'India', 'Australia'],
    'date': ['01-01', '01-01', '01-01', '02-01', '02-01', '02-01', '03-01', '03-01', '03-01', '04-01',
             '04-01', '04-01', '05-01', '05-01', '05-01', '06-01', '06-01', '06-01', '07-01', '07-01',
             '08-01', '08-01', '08-01', '09-01', '09-01', '09-01', '10-01', '10-01', '10-01', '11-01'],
    'valence': [0.94, 0.89, 0.85, 0.71, 0.67, 0.63, 0.81, 0.79, 0.77, 0.65,
                0.62, 0.61, 0.75, 0.72, 0.69, 0.85, 0.82, 0.79, 0.75, 0.72,
                0.91, 0.88, 0.84, 0.81, 0.78, 0.74, 0.9, 0.87, 0.83, 0.8]
})

def create_choropleth(data, year):
    fig = go.Figure()

    for date in data['date'].unique():
        df = data[data['date'] == date]
        fig.add_trace(go.Choropleth(
            locations=df['region'],
            z=df['valence'],
            locationmode='country names',
            colorscale='Viridis',
            colorbar_title='Valence',
            visible=False
        ))

    steps = []
    for i, date in enumerate(data['date'].unique()):
        step = dict(
            method='update',
            args=[{'visible': [False] * len(fig.data)}],
            label=date
        )
        step['args'][0]['visible'][i] = True
        steps.append(step)

    sliders = [dict(
        active=0,
        pad={"t": 50},
        steps=steps
    )]

    fig.update_layout(
        sliders=sliders,
        updatemenus=[
            dict(
                buttons=[
                    dict(label='2019',
                         method='update',
                         args=[{'visible': [i < len(data_2019['date'].unique()) for i in range(len(fig.data))]}]),
                    dict(label='2020',
                         method='update',
                         args=[{'visible': [i >= len(data_2019['date'].unique()) for i in range(len(fig.data))]}])
                ],
                direction="down",
                pad={"r": 10, "t": 10},
                showactive=True,
            ),
        ]
    )

    return fig

fig = create_choropleth(data_2019, 2019)
fig_2020 = create_choropleth(data_2020, 2020)

for trace in fig_2020.data:
    fig.add_trace(trace)

fig.show()

但是,数据选择不起作用:它要么始终显示 2020 年的数据,要么将两者混合在一起。 如何确保如果选择 2019 年,则相应数据仅显示 2019 年的数据,如果选择 2020 年,则仅显示 2020 年的数据?

python pandas animation plotly plotly-python
1个回答
0
投票

试试这个:

import plotly.graph_objects as go
import pandas as pd

data_2019 = pd.DataFrame({
    'year': 2019,
    'region': ['Germany', 'Denmark', 'Japan', 'France', 'Italy', 'Spain', 'Canada', 'Brazil', 'India', 'Australia',
               'China', 'Russia', 'South Korea', 'Netherlands', 'Sweden', 'Norway', 'Finland', 'Mexico',
               'Argentina', 'Chile',
               'Germany', 'Denmark', 'Japan', 'France', 'Italy', 'Spain', 'Canada', 'Brazil', 'India', 'Australia'],
    'date': ['01-01', '01-01', '01-01', '02-01', '02-01', '02-01', '03-01', '03-01', '03-01', '04-01',
             '04-01', '04-01', '05-01', '05-01', '05-01', '06-01', '06-01', '06-01', '07-01', '07-01',
             '08-01', '08-01', '08-01', '09-01', '09-01', '09-01', '10-01', '10-01', '10-01', '11-01'],
    'valence': [0.3, 0.25, 0.22, 0.21, 0.18, 0.15, 0.1, 0.12, 0.14, 0.15,
                0.17, 0.19, 0.21, 0.23, 0.25, 0.27, 0.29, 0.31, 0.33, 0.35,
                0.37, 0.39, 0.41, 0.43, 0.45, 0.47, 0.49, 0.51, 0.53, 0.55]
})

data_2020 = pd.DataFrame({
    'year': 2020,
    'region': ['Germany', 'Denmark', 'Japan', 'France', 'Italy', 'Spain', 'Canada', 'Brazil', 'India', 'Australia',
               'China', 'Russia', 'South Korea', 'Netherlands', 'Sweden', 'Norway', 'Finland', 'Mexico',
               'Argentina', 'Chile',
               'Germany', 'Denmark', 'Japan', 'France', 'Italy', 'Spain', 'Canada', 'Brazil', 'India', 'Australia'],
    'date': ['01-01', '01-01', '01-01', '02-01', '02-01', '02-01', '03-01', '03-01', '03-01', '04-01',
             '04-01', '04-01', '05-01', '05-01', '05-01', '06-01', '06-01', '06-01', '07-01', '07-01',
             '08-01', '08-01', '08-01', '09-01', '09-01', '09-01', '10-01', '10-01', '10-01', '11-01'],
    'valence': [0.94, 0.89, 0.85, 0.71, 0.67, 0.63, 0.81, 0.79, 0.77, 0.65,
                0.62, 0.61, 0.75, 0.72, 0.69, 0.85, 0.82, 0.79, 0.75, 0.72,
                0.91, 0.88, 0.84, 0.81, 0.78, 0.74, 0.9, 0.87, 0.83, 0.8]
})

def create_choropleth(data_2019, data_2020):
    fig = go.Figure()

    # Add traces for 2019
    for date in data_2019['date'].unique():
        df = data_2019[data_2019['date'] == date]
        fig.add_trace(go.Choropleth(
            locations=df['region'],
            z=df['valence'],
            locationmode='country names',
            colorscale='Viridis',
            colorbar_title='Valence',
            visible=False,
            name=f'2019 {date}'
        ))

    # Add traces for 2020
    for date in data_2020['date'].unique():
        df = data_2020[data_2020['date'] == date]
        fig.add_trace(go.Choropleth(
            locations=df['region'],
            z=df['valence'],
            locationmode='country names',
            colorscale='Viridis',
            colorbar_title='Valence',
            visible=False,
            name=f'2020 {date}'
        ))

    steps = []
    for i, date in enumerate(data_2019['date'].unique()):
        step = dict(
            method='update',
            args=[{'visible': [False] * len(fig.data)}],
            label=date
        )
        step['args'][0]['visible'][i] = True  # Show 2019 date
        step['args'][0]['visible'][i + len(data_2019['date'].unique())] = True  # Show 2020 date
        steps.append(step)

    sliders = [dict(
        active=0,
        pad={"t": 50},
        steps=steps
    )]

    updatemenus = [
        dict(
            buttons=[
                dict(label='2019',
                     method='update',
                     args=[{'visible': [i < len(data_2019['date'].unique()) for i in range(len(fig.data))]}]),
                dict(label='2020',
                     method='update',
                     args=[{'visible': [i >= len(data_2019['date'].unique()) for i in range(len(fig.data))]}])
            ],
            direction="down",
            pad={"r": 10, "t": 10},
            showactive=True,
            x=0.1,
            xanchor="left",
            y=1.1,
            yanchor="top"
        ),
    ]

    fig.update_layout(
        sliders=sliders,
        updatemenus=updatemenus,
        title_text='Valence by Country and Date',
        geo=dict(
            showframe=False,
            showcoastlines=True,
            projection_type='equirectangular'
        )
    )

    fig.data[0].visible = True

    return fig

fig = create_choropleth(data_2019, data_2020)
fig.show()
© www.soinside.com 2019 - 2024. All rights reserved.