Plotly:如何显示和过滤具有多个下拉菜单的数据框?

2023-11-27

我是 Python、Pandas 和 Plotly 的新手,所以也许答案很简单,但我在论坛或其他地方找不到任何内容……

我不想使用 Dash 也不想使用 ipywidgets,因为我希望能够使用plotly.offline.plot 以 HTML 形式导出(我需要一个交互式 HTML 文件来动态控制图形,而无需像 Dash 那样运行任何服务器)。

好吧,我的问题是我想使用几个(累积)下拉按钮(本例中为 2 个,但是可能更多)通过使用下拉列表中选定的值过滤原始数据。

num label   color   value
1   A       red     0.4
2   A       blue    0.2
3   A       green   0.3
4   A       red     0.6
5   A       blue    0.7
6   A       green   0.4
7   B       blue    0.2
8   B       green   0.4
9   B       red     0.4
10  B       green   0.2
11  C       red     0.1
12  C       blue    0.3
13  D       red     0.8
14  D       blue    0.4
15  D       green   0.6
16  D       yellow  0.5

在此示例中,如果我选择标签“A”和颜色“红色”,我只想显示标签“A”和颜色“红色”的行的值,如下所示:

num label   color   value
1   A       red     0.4
4   A       red     0.6

那么,该图应该只显示 2 个值

1)这是我目前的代码(见下文),但我不知道如何继续。你有什么主意吗 ?

2)额外问题:是否可以使用复选框而不是下拉列表,以便能够在条件内选择多个值,例如:标签过滤器可以是 A 或 B,而不仅仅是列表中的一个……

在此先感谢您的帮助 !

import pandas as pd
import plotly.graph_objects as go

d = {
    'num' : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
    'label' : ['A', 'A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'C', 'C', 'D', 'D', 'D', 'D'],
    'color' : ['red', 'blue', 'green', 'red', 'blue', 'green', 'blue', 'green', 'red', 'green', 'red', 'blue', 'red', 'blue', 'green', 'yellow'],
    'value' : [0.4, 0.2, 0.3, 0.6, 0.7, 0.4, 0.2, 0.4, 0.4, 0.2, 0.1, 0.3, 0.8, 0.4, 0.6, 0.5]
    }

# Build dataframe
df = pd.DataFrame(data=d)

# Build dropdown Labels
labels = df["label"].unique()
buttonsLabels = [dict(label = "All labels",
                            method = "restyle",
                            args = [{'y' : [df["value"] * 100]}] # or what else ?
                            )]
for label in labels:
    buttonsLabels.append(dict(label = label,
                              method = "restyle",
                              visible = True,
                              #args = [{'y' : ??? }]
                              ))
# Build dropdown Colors
colors = df["color"].unique()
buttonsColors = [dict(label = "All colors",
                            method = "restyle",
                            args = [{'y' : [df["value"] * 100]}] # or what else ?
                            )]
for color in colors:
    buttonsColors.append(dict(label = color,
                              method = "restyle",
                              visible = True,
                              # args = [{'y' : ??? }]
                              ))

# Display figure
fig = go.Figure(data = [ go.Scatter(x = df["num"], y = df["value"] * 100 ) ])

fig.update_layout(updatemenus = [
   dict(buttons = buttonsLabels, showactive = True),
   dict(buttons = buttonsColors, showactive = True, y = 0.8)
   ])

fig.show()

当然可以显示和过滤具有多个下拉列表的数据框。下面的代码片段将完全为您做到这一点。该代码片段与您提供的代码有很多共同点,但我必须从头开始构建它以确保一切协调一致。运行下面的代码片段,然后选择A and Red看看你实际上会得到:

num label   color   value
1   A       red     0.4
4   A       red     0.6

Plot:

enter image description here

还有改进的空间。当我有时间的时候,我会完善代码并改进布局。首先,请告诉我这是否确实是您所寻找的。

完整代码:

# Imports
import plotly.graph_objs as go
import pandas as pd
import numpy as np

# source data
df = pd.DataFrame({0: {'num': 1, 'label': 'A', 'color': 'red', 'value': 0.4},
                    1: {'num': 2, 'label': 'A', 'color': 'blue', 'value': 0.2},
                    2: {'num': 3, 'label': 'A', 'color': 'green', 'value': 0.3},
                    3: {'num': 4, 'label': 'A', 'color': 'red', 'value': 0.6},
                    4: {'num': 5, 'label': 'A', 'color': 'blue', 'value': 0.7},
                    5: {'num': 6, 'label': 'A', 'color': 'green', 'value': 0.4},
                    6: {'num': 7, 'label': 'B', 'color': 'blue', 'value': 0.2},
                    7: {'num': 8, 'label': 'B', 'color': 'green', 'value': 0.4},
                    8: {'num': 9, 'label': 'B', 'color': 'red', 'value': 0.4},
                    9: {'num': 10, 'label': 'B', 'color': 'green', 'value': 0.2},
                    10: {'num': 11, 'label': 'C', 'color': 'red', 'value': 0.1},
                    11: {'num': 12, 'label': 'C', 'color': 'blue', 'value': 0.3},
                    12: {'num': 13, 'label': 'D', 'color': 'red', 'value': 0.8},
                    13: {'num': 14, 'label': 'D', 'color': 'blue', 'value': 0.4},
                    14: {'num': 15, 'label': 'D', 'color': 'green', 'value': 0.6},
                    15: {'num': 16, 'label': 'D', 'color': 'yellow', 'value': 0.5},
                    16: {'num': 17, 'label': 'E', 'color': 'purple', 'value': 0.68}}
                    ).T

df_input = df.copy()

# split df by labels
labels = df['label'].unique().tolist()
dates = df['num'].unique().tolist()

# dataframe collection grouped by labels
dfs = {}
for label in labels:
    dfs[label]=pd.pivot_table(df[df['label']==label],
                                    values='value',
                                    index=['num'],
                                    columns=['color'],
                                    aggfunc=np.sum)

# find row and column unions
common_cols = []
common_rows = []
for df in dfs.keys():
    common_cols = sorted(list(set().union(common_cols,list(dfs[df]))))
    common_rows = sorted(list(set().union(common_rows,list(dfs[df].index))))

# find dimensionally common dataframe
df_common = pd.DataFrame(np.nan, index=common_rows, columns=common_cols)

# reshape each dfs[df] into common dimensions
dfc={}
for df_item in dfs:
    #print(dfs[unshaped])
    df1 = dfs[df_item].copy()
    s=df_common.combine_first(df1)
    df_reshaped = df1.reindex_like(s)
    dfc[df_item]=df_reshaped

# plotly start 
fig = go.Figure()
# one trace for each column per dataframe: AI and RANDOM
for col in common_cols:
    fig.add_trace(go.Scatter(x=dates,
                             visible=True,
                             marker=dict(size=12, line=dict(width=2)),
                             marker_symbol = 'diamond',name=col
                  )
             )

# menu setup    
updatemenu= []

# buttons for menu 1, names
buttons=[]

# create traces for each color: 
# build argVals for buttons and create buttons
for df in dfc.keys():
    argList = []
    for col in dfc[df]:
        #print(dfc[df][col].values)
        argList.append(dfc[df][col].values)
    argVals = [ {'y':argList}]

    buttons.append(dict(method='update',
                        label=df,
                        visible=True,
                        args=argVals))

# buttons for menu 2, colors
b2_labels = common_cols

# matrix to feed all visible arguments for all traces
# so that they can be shown or hidden by choice
b2_show = [list(b) for b in [e==1 for e in np.eye(len(b2_labels))]]
buttons2=[]
buttons2.append({'method': 'update',
                 'label': 'All',
                 'args': [{'visible': [True]*len(common_cols)}]})

# create buttons to show or hide
for i in range(0, len(b2_labels)):
    buttons2.append(dict(method='update',
                        label=b2_labels[i],
                        args=[{'visible':b2_show[i]}]
                        )
                   )

# add option for button two to hide all
buttons2.append(dict(method='update',
                        label='None',
                        args=[{'visible':[False]*len(common_cols)}]
                        )
                   )

# some adjustments to the updatemenus
updatemenu=[]
your_menu=dict()
updatemenu.append(your_menu)
your_menu2=dict()
updatemenu.append(your_menu2)
updatemenu[1]
updatemenu[0]['buttons']=buttons
updatemenu[0]['direction']='down'
updatemenu[0]['showactive']=True
updatemenu[1]['buttons']=buttons2
updatemenu[1]['y']=0.6

fig.update_layout(showlegend=False, updatemenus=updatemenu)
fig.update_layout(yaxis=dict(range=[0,df_input['value'].max()+0.4]))

# title
fig.update_layout(
    title=dict(
        text= "<i>Filtering with multiple dropdown buttons</i>",
        font={'size':18},
        y=0.9,
        x=0.5,
        xanchor= 'center',
        yanchor= 'top'))

# button annotations
fig.update_layout(
    annotations=[
        dict(text="<i>Label</i>", x=-0.2, xref="paper", y=1.1, yref="paper",
            align="left", showarrow=False, font = dict(size=16, color = 'steelblue')),
        dict(text="<i>Color</i>", x=-0.2, xref="paper", y=0.7, yref="paper",
            align="left", showarrow=False, font = dict(size=16, color = 'steelblue')

                             )
    ])

fig.show()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Plotly:如何显示和过滤具有多个下拉菜单的数据框? 的相关文章

随机推荐

  • 如何在一个会话中发送多封电子邮件?

    我想要向不同的收件人发送数千封不同的电子邮件 并且想要打开与我的 SMTP 的连接并保留它 我希望这比重新打开 ervy 邮件的连接更快 我想使用 Apache Commons Email 但如果需要的话可以回退到 Java Mail AP
  • python-vlc 不会启动播放器

    好的 开始吧 我正在尝试播放在线视频 我得到了网址 如下所示 http fsi stanford edu sites default files video 4 mp4它不是我将在我的应用程序中使用的东西 但它只是一个示例文件 阅读 pyt
  • 使用自定义签名定义保存 TF2 keras 模型

    我有一个 Keras 顺序 模型 可以使用 Tensorflow 1 13 中的自定义签名定义进行保存 如下所示 from tensorflow saved model utils import build tensor info from
  • 在 Windows 上安装用于 ruby​​ 的 ncurses

    我正在尝试在 Windows 上为 ruby 安装 ncurses 我之前没有在我的机器上安装过 ncurses 我认为拥有 红宝石开发套件 它要求就足够了 但现在我被要求指定选项 我不知道该选择哪些选项 或者我是否需要执行 安装其他操作才
  • Swift 3 以编程方式创建 UILabel 并添加 NSLayoutConstraints

    您好 我正在尝试以编程方式创建一个标签并添加 NSLayoutConstraints 以便无论屏幕大小和方向等如何 它都位于超级视图的中心 我已经看过 但只是找不到可以遵循的示例 这是我所拥有的 let codedLabel UILabel
  • 如何根据数字范围过滤数组?

    我有一个用这个函数过滤的数组 function filter arr criteria return arr filter function obj return Object keys criteria every function c
  • Android:如何将带有空格的 URL 字符串解析为 URI 对象?

    我有一个表示包含空格的 URL 的字符串 并希望将其转换为 URI 对象 如果我只是尝试通过创建它 String myString http myhost com media File Name that has spaces inside
  • Codeigniter 中的路由 - 404 页面未找到

    有人能告诉我 问题出在哪里吗 这是我的控制器 class Support extends CI Controller public function construct parent construct this gt load gt mo
  • 当向量增长时如何强制移动语义?

    我有一个std vector某个类的对象A 该类非常重要并且具有复制构造函数and移动定义的构造函数 std vector a myvec 如果我用以下内容填充向量A对象 例如使用myvec push back a 使用复制构造函数 向量的
  • 如何从 jQuery 触发模拟点击 ng Click

    如何有一个像这样的链接 a href Some text a 我想调用ngClick来自 jQuery 的操作 a click 但它不起作用 someAction 没有被调用 也没有起作用 a trigger click 是否可以调用som
  • 通过 Web Audio API 播放分块音频时断断续续/听不清

    我在上一篇文章中提出了这一点 但由于它与原始问题无关 所以我将其单独发布 我无法通过网络音频播放传输的音频 就像在媒体播放器中播放一样 我尝试了两种不同的传输协议 binaryjs 和 socketio 但在尝试通过网络音频播放时都没有什么
  • Angular 和 Ionic、HTTP Get 在真实设备 IOS 中不起作用

    我的应用程序出现问题 当我在本地主机中运行该应用程序时 它工作正常 我可以看到频道列表 但当我尝试通过物理设备测试该应用程序时 它没有显示任何内容 我认为问题出在我用来通过http发送json数据的方法上 function use stri
  • 您建议使用哪种 Python 方式来检查 whois 数据库记录?

    我正在尝试启动并运行一个实际上需要检查 whois 数据库的网络服务 我现在正在做的事情很丑陋 我想尽可能避免它 我调用 gwhois 命令并解析它的输出 丑陋的 我做了一些搜索 试图找到一种Python式的方法来完成这项任务 一般来说我什
  • 位域的 GCC 实现中的一个错误

    在 C11 中工作 以下结构 struct S unsigned a 4 Bool b 1 被 GCC 列为unsigned 4 个字节 其中使用了 4 位 后面跟着一个 Bool 4 个字节 其中使用 1 位 总大小为 8 个字节 请注意
  • IPTC .NET 读/写 C# 库

    我正在寻找一些库来从 Jpg 文件读取 写入 IPTC 元数据 开源还是付费 并不重要 它应该与 NET 3 5 和 c 一起使用 有人知道这样的图书馆吗 我用谷歌搜索但没有找到任何东西 http msdn microsoft com en
  • 在 Google Apps 脚本上运行 WebAssembly

    我正在尝试在新的 V8 Google Apps 脚本运行时上运行 WebAssembly 它似乎受支持 但异步函数似乎在返回 Promise 后终止 let wasm new Uint8Array snip buffer function
  • Spring Security 的基本身份验证重定向到 /error 以获取无效凭据

    我有一个使用基本身份验证与 Spring Security 一起运行的 Spring Boot 应用程序 当提供正确的基本身份验证凭据时 一切都很好 但是对于不正确的身份验证凭据 Spring 会提供一个HttpRequestMethodN
  • 解决失去对 self 类型约束的支持的问题

    这是我在旧版本的 TypeScript 中一直在做的事情 并且我在 C 中使用此方法 但它在最新的 1 0 版本的 TypeScript 中不起作用 这是过去有效的方法 class Base
  • 哪种网络应用程序实际上会受到浮动错误的影响?

    有一种简单的方法可以完全锁定大量 JVM class runhang public static void main String args System out println Test double d Double parseDoub
  • Plotly:如何显示和过滤具有多个下拉菜单的数据框?

    我是 Python Pandas 和 Plotly 的新手 所以也许答案很简单 但我在论坛或其他地方找不到任何内容 我不想使用 Dash 也不想使用 ipywidgets 因为我希望能够使用plotly offline plot 以 HTM