I'm trying to add filter selection to my Plotly Bar. Here's the working Code:
import plotly.express as px
import plotly.graph_objects as go
# from plotly.subplots import make_subplots
import plotly as py
import pandas as pd
from plotly import tools
d = {'Mkt_cd': ['Mkt1','Mkt2','Mkt3','Mkt4','Mkt5','Mkt1','Mkt2','Mkt3','Mkt4','Mkt5'],
'Category': ['Apple','Orange','Grape','Mango','Orange','Mango','Apple','Grape','Apple','Orange'],
'CategoryKey': ['Mkt1Apple','Mkt2Orange','Mkt3Grape','Mkt4Mango','Mkt5Orange','Mkt1Mango','Mkt2Apple','Mkt3Grape','Mkt4Apple','Mkt5Orange'],
'Current': [15,9,20,10,20,8,10,21,18,14],
'Goal': [50,35,21,44,20,24,14,29,28,19],
'Q1': [30,25,11,34,10,14,4,19,8,9]
}
dataset = pd.DataFrame(d)
grouped = dataset.groupby('Category', as_index=False).sum()
data = grouped.to_dict(orient='list')
v_cat = grouped['Category'].tolist()
v_current = grouped['Current']
v_goal = grouped['Goal']
v_q1 = grouped['Q1']
fig = go.Figure()
fig.add_trace(go.Bar(
x=v_current,
y=v_cat,
marker_color="#ff0000",
orientation='h',
width=0.25
))
for i, g in enumerate(v_goal):
a=fig.add_shape(type="rect",
x0=g+0.5, y0=v_cat[i], x1=g, y1=v_cat[i],
line=dict(color='#636EFA', width = 58))
for i, g in enumerate(v_q1):
b=fig.add_shape(type="rect",
x0=g+0.5, y0=v_cat[i], x1=g, y1=v_cat[i],
line=dict(color='#636EFA', width = 58))
#Adding Buttons here, first for Mkt_cd
buttons = []
groups = dataset['Mkt_cd'].unique().tolist()
frame={}
for i in groups:
frame[str(i)]=dataset[dataset['Mkt_cd']==i]
for k in frame.keys():
buttons.append(dict(method='restyle',label=k,
args=[{'y':[frame[str(k)]['Mkt_cd'].values],
'type':'bar'}, [0]],
)
)
updatemenu = []
your_menu = dict()
updatemenu.append(your_menu)
updatemenu[0]['buttons'] = buttons
updatemenu[0]['direction'] = 'down'
updatemenu[0]['showactive'] = True
fig.update_layout(barmode='relative', updatemenus=updatemenu)
fig.show()
My dataset is in un-aggregated form at the Key level. I group it together at the Category level with Grouped. I want to add two filters:
1st) Mkt_Cd filter. User should be able to select their market and see how their categories are doing in their markets. This should ideally be a multi-select filter where you can add a bunch of markets and see how the numbers are looking, and it should also filter the Goals and Q1 numbers
2nd) Goals Filter. Users should be able to select which trace they want to look at when it comes to the Goals (Goal or Q1 for now but in the future, Q2, Q3 as well). Again, ideally a multiselector.
Something like this:
I was able to add a clunky Mkt_cd filter but as you can see it's broken :P and there's no way of resetting the view. I did not even try to attempt the Goals filter! Any help will be appreciated.




