St.plotly_chart with stacked bar chart: How to select entire stack with one click?

Hi,

Based on what I’ve seen online, I have a pretty unique problem that I’d really appreciate some help and/or guidance on.

I am trying to create a stacked barplot in Plotly, such that when the user clicks on one of the bars, I want all of the stacked bars at that x-axis tick to be selected. In other words, I want the user to be able to make selections based only on x-axis values, rather than x-axis and legend values.

At the moment, the user can only select one item at a time (of course they can also hold down shift, but I want to avoid that). I’ve tried using legendgroups, but that hasn’t worked.

This is the current behaviour (based on clicking on Group 1, category A):

And this is the desired behaviour (based on clicking on Group 1, category A):

I’d really appreciate any help or guidance you guys might be able to provide me with - I’m also not that attached to Plotly, so if a solution could better be reached using a different package, then please let me know :slight_smile:

Here is the code I used:

import streamlit as st
import plotly.graph_objects as go


def set_val():
    st.session_state.testing = st.session_state.selection

if 'testing' not in st.session_state:
    st.session_state.testing = ''

# Sample data
categories = ['A', 'B', 'C', 'D']
group_1 = [10, 15, 7, 5]
group_2 = [13, 9, 12, 8]
group_3 = [7, 5, 11, 10]

# Create traces for each group
trace1 = go.Bar(x=categories, y=group_1, name='Group 1', legendgroup='1')
trace2 = go.Bar(x=categories, y=group_2, name='Group 2', legendgroup='1')
trace3 = go.Bar(x=categories, y=group_3, name='Group 3', legendgroup='1')

# Layout configuration with grouped legend
layout = go.Layout(
    barmode='stack',  # Group bars together
    title='Grouped Bar Chart Example',
    xaxis=dict(title='Categories'),
    yaxis=dict(title='Values'),
    legend=dict(title='Groups', groupclick = 'togglegroup')  # Legend title
)

# Create the figure
fig = go.Figure(data=[trace1, trace2, trace3], layout=layout)

# Display the plotly chart
chart = st.plotly_chart(fig, use_container_width=True, key='selection', on_select=set_val)