Barchart Grouped Mode Trying to use the pattern_shape

I am trying to run the below code:

import pandas as pd
import plotly.express as px

Sample DataFrame

df = pd.DataFrame({
‘Category’: [‘A’, ‘A’, ‘B’, ‘B’],
‘Subgroup’: [‘X’, ‘Y’, ‘X’, ‘Y’],
‘Value’: [10, 15, 8, 12],
‘Flag’: [‘Winner’, ‘Loser’, ‘Loser’, ‘Winner’]
})

Create a grouped bar chart

fig = px.bar(
df,
x=‘Category’,
y=‘Value’,
color=‘Subgroup’,
barmode=‘group’,
# Use ‘Flag’ to determine which pattern to apply
pattern_shape=‘Flag’,
# Pattern shapes are applied in the order ‘Winner’, ‘Loser’, etc.
# If your data’s first Flag category is “Winner”, it will get the first shape, second gets the next, etc.
pattern_shape_sequence=[‘/’, ‘\’],
# Title for clarity
title=‘Example of pattern_shape_sequence in a grouped bar chart’
)

It is showing me the below image. How can I fix the gap between bars?

Thank you.

Hi @kusha,

welcome to the forum!

I could reproduce your problem and figure out, that the gap disappears when removing the pattern shape. Maybe some else from the community can help on this? Is this a bug?:

import pandas as pd
import plotly.express as px


df = pd.DataFrame({
    "Category": ["A", "A", "B", "B"],
    "Subgroup": ["X", "Y", "X", "Y"],
    "Value": [10, 15, 8, 12],
    "Flag": ["Winner", "Loser", "Loser", "Winner"]
})

fig = px.bar(
    df,
    x="Category",
    y="Value",
    color="Subgroup",
    barmode="group",
    #pattern_shape="Flag",
    #pattern_shape_sequence=['/', '\\'],
    title="Example of pattern_shape_sequence in a grouped bar chart"
)


fig.show()

If the pattern is mandatory I would suggest using plotlys.graph_objects library to create the same result but with pattern shapes. See below:

import pandas as pd
import plotly.graph_objects as go


df = pd.DataFrame({
    "Category": ["A", "A", "B", "B"],
    "Subgroup": ["X", "Y", "X", "Y"],
    "Value": [10, 15, 8, 12],
    "Flag": ["Winner", "Loser", "Loser", "Winner"]
})


pattern_dict = {"Winner": "/", "Loser": "\\"}

fig = go.Figure()

for subgroup in df["Subgroup"].unique():
    sub_df = df[df["Subgroup"] == subgroup]
    fig.add_trace(go.Bar(
        x=sub_df["Category"],
        y=sub_df["Value"],
        name=subgroup,
        marker=dict(
            pattern_shape=[pattern_dict[flag] for flag in sub_df["Flag"]]
        )
    ))

fig.update_layout(
    {
        "barmode" : "group",
        "title" : "Example of pattern_shape_sequence in a grouped bar chart"
    }
)

fig.show()

Hope I could help.