如何在 Python 和 Plotly 中使用下拉菜单进行数据选择

How to use dropdown for data selection in Python and Plotly

我已经将数据分为 2 个以上的组。然后,我使用分组条形图绘制它,使用 plotly 绘制一组特定的 2 组。如何创建 2 个下拉菜单 select 哪个组要绘制为 trace1,哪个组要绘制为 trace2?

下面的示例使用硬编码组 1 进行跟踪 1,使用组 2 进行跟踪 2。我想用下拉菜单控制这些。

import pandas as pd
import plotly as py
import plotly.graph_objs as go

d = {'x': ['a','b','c','a','b','c','a','b','c'], 'y': [1,2,3,10,20,30,100,200,300], 'group': [1,1,1,2,2,2,3,3,3]}
df = pd.DataFrame(data=d)


trace1 = go.Bar(
    x=df['x'],
    y=df[df['group']==1].y,
    name='trace1'
)
trace2 = go.Bar(
    x=df['x'],
    y=df[df['group']==2].y,
    name='trace2'
)
data = [trace1, trace2]
layout = go.Layout(
    barmode='group'
)

fig = go.Figure(data=data, layout=layout)
py.offline.plot(fig, filename='grouped-bar')

剧情:

以下建议应该可以让您完全按照自己的意愿行事。 仅 select 使用两个下拉菜单的跟踪源:

绘图 1 - 选择是第 1 组与第 1 组:

绘图 2 - 选择第 2 组与第 3 组:

代码:

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

# data
d = {'x': ['a','b','c','a','b','c','a','b','c'], 'y': [1,2,3,10,20,30,100,200,300], 'group': [1,1,1,2,2,2,3,3,3]}
df = pd.DataFrame(data=d)

# split df by groups and organize them in a dict
groups = df['group'].unique().tolist()
dfs={}
for g in groups:
    dfs[str(g)]=df[df['group']==g]

# get column names from first dataframe in the dict
#colNames = list(dfs[list(dfs.keys())[0]].columns)
#colNames=colNames[:2]


# one trace for each column per dataframe
fig=go.Figure()

# set up the first trace
fig.add_trace(go.Bar(x=dfs['1']['x'],
                             y=dfs['1']['y'],
                             visible=True)
             )
# set up the second trace
fig.add_trace(go.Bar(x=dfs['1']['x'],
                             y=dfs['1']['y'],)
             )

#f=fig.to_dict()

# plotly start
# buttons for menu 1, names
updatemenu=[]
buttons=[]

# button with one option for each dataframe
for df in dfs.keys():
    #print(b, df)
    buttons.append(dict(method='restyle',
                        label=df,
                        visible=True,
                        args=[{'y':[dfs[str(df)]['y'].values],
                               'type':'bar'}, [0]],
                        )
                  )

# another button with one option for each dataframe
buttons2=[]
for df in dfs.keys():
    buttons2.append(dict(method='restyle',
                        label=df,
                        visible=True,
                        args=[{'y':[dfs[str(df)]['y'].values],
                               'type':'bar'}, [1]],
                        )
                  )

# 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.5

# add dropdown menus to the figure
fig.update_layout(showlegend=False, updatemenus=updatemenu)

# add notations to the dropdown menus
fig.update_layout(
    annotations=[
        go.layout.Annotation(text="<b>group/<br>trace:</b>",
                             x=-0.15, xref="paper",
                             y=1.15, yref="paper",
                             align="left", showarrow=False),
        go.layout.Annotation(text="<b>group/<br>trace:</b>",
                             x=-0.15, xref="paper", y=0.6,
                             yref="paper", showarrow=False),
                  ]
)

fig.show()