以下建议应该可以让您完全按照您的要求进行操作。只需使用两个下拉菜单选择跟踪源:
情节 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()