DEV Community

Discussion on: Stacked and Grouped Bar Charts Using Plotly (Python)

Collapse
 
tigerwhoo profile image
tigerwhoo • Edited

Hi Let say if I have more than 2 elements to stack, how do I get about doing it ?

I having problem doing a 3 elements stack. The stacked chart does not give me the correct value.

Collapse
 
fronkan profile image
Fredrik Sjöstrand • Edited

Hello!
I have adapted my example for using 3 elements in the stack. I pasted the entire code here in the comment. But what you need to focus on is how you add on mode go.Bar object. It should have the same offset group but the base must be a list where each element is the sum of the two previous bars at the same position. Here I use a list comprehension for this, [val1+val2 for val1, val2 in zip(data["model_1"],data["model_2"])]

data = {
    "original":[15, 23, 32, 10, 23],
    "model_1": [4,   8, 18,  6,  0],
    "model_2": [11, 18, 18,  0,  20],
    "model_3": [20, 10, 9,  6,  10],
    "labels": [
        "feature",
        "question",
        "bug",
        "documentation",
        "maintenance"
    ]
}

fig = go.Figure(
    data=[
        go.Bar(
            name="Original",
            x=data["labels"],
            y=data["original"],
            offsetgroup=0,
        ),
        go.Bar(
            name="Model 1",
            x=data["labels"],
            y=data["model_1"],
            offsetgroup=1,
        ),
        go.Bar(
            name="Model 2",
            x=data["labels"],
            y=data["model_2"],
            offsetgroup=1,
            base=data["model_1"],
        ),
        # NEW CODE
        go.Bar(
            name="Model 3",
            x=data["labels"],
            y=data["model_3"],
            offsetgroup=1,
            base=[val1+val2 for val1, val2 in zip(data["model_1"],data["model_2"])],
        )
        # END NEW CODE
    ],
    layout=go.Layout(
        title="Issue Types - Original and Models",
        yaxis_title="Number of Issues"
    )
)

fig.show()
Collapse
 
tigerwhoo profile image
tigerwhoo

Hello Fredrik,
Thanks for the pointer. Did not expect that I need to use list comprehension for base that have more than 3 elements to stack.

Yeah, this cleared my doubt.

Thanks

Thread Thread
 
fronkan profile image
Fredrik Sjöstrand

No problem! Glad I could help 😄