Plotly:如何使用下拉菜单过滤 Pandas 数据框? [英] Plotly: How to filter a pandas dataframe using a dropdown menu?

查看:71
本文介绍了Plotly:如何使用下拉菜单过滤 Pandas 数据框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a dataframe and using plotly I want to visualise the data. I have the following code

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

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

It's really messy, so I want a drop-down menu where the user can just select the vid_id and it only shows the 1 graph.

推荐答案

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

You can set up one trace and a button option for each individual trace. This will turn this figure...

...进入这个:

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

The button option A will be replaced with the first column in your dataframe. And the dropdown menu will let you choose which column to display in your figure.

代码:

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

这篇关于Plotly:如何使用下拉菜单过滤 Pandas 数据框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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