[Python] Issue with plotly dash filters

Discussão em 'Python' iniciado por Stack, Abril 29, 2025.

  1. Stack

    Stack Membro Participativo

    I'm using the following script to generate a stacked and grouped bar plot.

    from plotly import graph_objects as go

    data = {
    "left": [
    {"original": 15, "model_1": 4, "model_2": 11},
    {"original": 23, "model_1": 8, "model_2": 18},
    {"original": 32, "model_1": 18, "model_2": 18},
    {"original": 10, "model_1": 6, "model_2": 0},
    {"original": 23, "model_1": 0, "model_2": 20}
    ],
    "right": [
    {"original": 7, "model_1": 3, "model_2": 5},
    {"original": 12, "model_1": 6, "model_2": 8},
    {"original": 15, "model_1": 8, "model_2": 10},
    {"original": 5, "model_1": 4, "model_2": 0},
    {"original": 10, "model_1": 2, "model_2": 12}
    ],
    "labels": [
    "feature",
    "question",
    "bug",
    "documentation",
    "maintenance"
    ]
    }

    fig = go.Figure()

    colors = {
    "original": "#636EFA",
    "model_1": "#EF553B",
    "model_2": "#00CC96"
    }

    def add_stacked_bar(side, offset_group):
    side_data = data[side]
    for i, category in enumerate(data["labels"]):
    current_base = 0
    for model_type in ["original", "model_1", "model_2"]:
    value = side_data.get(model_type, 0)
    if value > 0:
    fig.add_trace(go.Bar(
    name=f"{model_type.replace('_', ' ').title()} ({side.title()})",
    x=[category],
    y=[value],
    offsetgroup=offset_group,
    base=current_base,
    marker_color=colors[model_type],
    legendgroup=model_type,
    showlegend=(i == 0)
    ))
    current_base += value

    add_stacked_bar("left", 0)
    add_stacked_bar("right", 1)

    fig.update_layout(
    title="Issue Types - Original and Models",
    yaxis_title="Number of Issues",
    barmode='group',
    legend_title="Model Types",
    legend=dict(
    orientation="h",
    yanchor="bottom",
    y=1.02,
    xanchor="right",
    x=1
    )
    )


    Source: Double bar stacked bar plot in plotly dash

    The only issue is that when I filter the plot I end up with floating bars.

    [​IMG]

    One source I found said that changing the barmode from "group" to "stack" would fix the issue, but unfortunately it does not help. Is there a way to fix the bars when a filter is applied?

    Continue reading...

Compartilhe esta Página