情节:如何使用下拉菜单过滤熊猫数据框?

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

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

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

enter image description here

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

python plotly
1个回答
1
投票
您可以设置

one跟踪和每个单独跟踪的按钮选项。这将使这个数字...

enter image description here

...进入此:

enter image description here

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

代码:

import numpy as np import pandas as pd import plotly.express as px # 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(pd.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: #print(b, df) 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()
© www.soinside.com 2019 - 2024. All rights reserved.