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

时间:2019-03-18 17:08:10

标签: python plotly

我对数据进行了2组以上的分组。然后,我使用一组绘制的条形图将其绘制为一组特定的2组。如何创建2个下拉菜单,以选择将哪个组绘制为trace1,将哪个组绘制为trace2?

下面的示例对trace1使用硬编码的组1,对trace2使用硬编码的组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')

1 个答案:

答案 0 :(得分:1)

以下建议应该可以让您准确地完成所需的工作。 只需使用两个下拉菜单选择跟踪的来源:

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

enter image description here

图2-选择是第2组vs第3组:

enter image description here

代码:

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