TeoK
TeoK

Reputation: 501

stacked barplot in plotly

My input:

names_col = ['Count','Percentage']
dat = [['Matching', 63],['Mismatching', 37]]
plot_df = pd.DataFrame(data=dat,columns=names_col)

I just trying plot within plotly simple bar char where stacked. my code:

fig = px.bar(p_df, x='Count', y='Percentage', color='Count' ,title='My plot', barmode='stack')
fig.show();

And what I get:

enter image description here

That not what I expected. I want something like this:

enter image description here

Here code within seaborn:

    p=p_df.set_index('Count').T.plot(kind='bar', stacked=True, figsize=(12,8),rot=0) 
p.set_title('BBPS.2')
for x in p.containers:
    p.bar_label(x, label_type='edge', weight='bold')
    p.bar_label(x, label_type='center', weight='bold', color='white')
plt.show();

Upvotes: 1

Views: 17990

Answers (2)

ZXYNINE
ZXYNINE

Reputation: 752

You need to set the base to the first bar in order to stack them. Right now you have merely defined two separate bars. Take a look at this code from a dev.to post:

fig3 = 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"], 
        )
    ],
    layout=go.Layout(
        title="Issue Types - Original and Models",
        yaxis_title="Number of Issues"
    )
)
fig3.show()

That resulted in a plot that looks like this: enter image description here

Upvotes: 4

Adid
Adid

Reputation: 1584

By setting the x axis to 'Count' you are defining the bars to not be stacked.
You could either find a different parameter for the x axis or add a dummy column with the same value for both rows so they have the same x value:

import pandas as pd
import plotly.express as px

names_col = ['Count','Percentage', 'dummy']
dat = [['Matching', 63, 0],['Mismatching', 37, 0]]
plot_df = pd.DataFrame(data=dat,columns=names_col)
fig = px.bar(plot_df, x='dummy', y='Percentage', color='Count' ,title='My plot')
fig.show()

The result: Fixed stacked graph

Upvotes: 3

Related Questions