【问题标题】:Plotly: How to filter a pandas dataframe using a dropdown menu?Plotly:如何使用下拉菜单过滤熊猫数据框?
【发布时间】:2020-04-11 20:11:00
【问题描述】:

我有一个数据框并使用plotly 来可视化数据。我有以下代码

fig = px.line(df, x="row_num", y="audienceWatchRatio", color='vid_id')
fig.show() 

真的很乱,所以我想要一个下拉菜单,用户可以在其中选择vid_id,它只显示 1 个图表。

【问题讨论】:

    标签: python plotly plotly-python


    【解决方案1】:

    您可以为每个单独的跟踪设置一个跟踪和一个按钮选项。这将变成这个数字...

    ...进入这个:

    按钮选项A 将替换为数据框中的第一列。下拉菜单将让您选择要在图中显示的列。

    代码:

    import numpy as np
    import pandas as pd
    import plotly.graph_objects as go
    import datetime
    
    # mimic OP's datasample
    
    NPERIODS = 200
    
    np.random.seed(123)
    df = pd.DataFrame(np.random.randint(-10, 12, size=(NPERIODS, 4)),
                      columns=list('ABCD'))
    datelist = pd.date_range(datetime.datetime(2020, 1, 1).strftime('%Y-%m-%d'),
                             periods=NPERIODS).tolist()
    df['dates'] = datelist 
    df = df.set_index(['dates'])
    df.index = pd.to_datetime(df.index)
    df.iloc[0] = 0
    df = df.cumsum()
    
    # # plotly
    fig = go.Figure()
    
    # set up ONE trace
    fig.add_trace(go.Scatter(x=df.index,
                             y=df[df.columns[0]],
                             visible=True)
                 )
    
    updatemenu = []
    buttons = []
    
    # button with one option for each dataframe
    for col in df.columns:
        buttons.append(dict(method='restyle',
                            label=col,
                            visible=True,
                            args=[{'y':[df[col]],
                                   'x':[df.index],
                                   'type':'scatter'}, [0]],
                            )
                      )
    
    # some adjustments to the updatemenus
    updatemenu = []
    your_menu = dict()
    updatemenu.append(your_menu)
    
    updatemenu[0]['buttons'] = buttons
    updatemenu[0]['direction'] = 'down'
    updatemenu[0]['showactive'] = True
    
    # add dropdown menus to the figure
    fig.update_layout(showlegend=False, updatemenus=updatemenu)
    fig.show()
    

    【讨论】:

      猜你喜欢
      • 2021-12-02
      • 1970-01-01
      • 2021-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-28
      • 2019-01-17
      • 1970-01-01
      相关资源
      最近更新 更多