Setting the base in go.Bar to refresh when clicking on the legend

Hello all!

I’m attempting to create a custom grouped & stacked bar charts. I’ve managed to create them, however would love help on how to update the “base” of the stacked bars when clicking on the legend. At the moment, clicking on the legend to exclude certain groupings will reveal a chunk of empty space on the graph which is visually unappealing. I’ll link them below as well for reference.

Here is some reproducible code (just random data I’ve generated):

# Generate some random data
subgroups = ['Subgroup {}'.format(i+1) for i in range(5) for j in range(5) ] # Categories to stack 
bars = [i+1 for j in range(5) for i in range(5) ] # Bar x values 
vals = [random.randint(1,100) for j in range(5) for i in range(5)] # Group 1, Group 2 
vals_2  = [i+random.randint(20,50) for i in vals]

d1 = pd.DataFrame(columns = ["Subgroups","Index", "Values"])
d1["Subgroups"] = subgroups 
d1["Index"] = bars 
d1["Values"] = vals
pivot_d1 = pd.pivot_table(d1, index=['Index'], columns=['Subgroups'], values=['Values'])
pivot_d1.columns = pivot_d1.columns.set_levels(['Group 1'],level=0)

d2 = pd.DataFrame(columns = ["Subgroups","Index", "Values"])
d2["Subgroups"] = subgroups 
d2["Index"] = bars 
d2["Values"] = vals_2
pivot_d2 = pd.pivot_table(d2, index=['Index'], columns=['Subgroups'], values=['Values'])
pivot_d2.columns = pivot_d1.columns.set_levels(['Group 2'],level=0)

fig = go.Figure()

prev_base_1 = []
prev_base_2 = []
for i in pivot_d1.columns: 
                        , legendgroup=i[1]
                        , base=prev_base_1

        prev_base_1 += pivot_d1[i].copy()
        prev_base_1 = pivot_d1[i].copy()

for j in pivot_d2.columns: 
                         , legendgroup=j[1]
                         , base =prev_base_2
        prev_base_2 += pivot_d2[j].copy()
        prev_base_2 = pivot_d2[j].copy()

Including some references for what the output looks like:

Here’s what happens when you toggle the legends to exclude any values:
Excluding the bars for subgroup 4:

Excluding the bars for subgroup 3:

Any help will be greatly appreciated.