Is it possible to add hatches to each individual bar in seaborn.barplot?

You can loop over the bars created by catching the AxesSubplot returned by barplot, then looping over its patches. You can then set hatches for each individual bar using .set_hatch()

Here’s a minimal example, which is a modified version of the barplot example from here.

import matplotlib.pyplot as plt
import seaborn as sns

# Set style
sns.set(style="whitegrid", color_codes=True)

# Load some sample data
titanic = sns.load_dataset("titanic")

# Make the barplot
bar = sns.barplot(x="sex", y="survived", hue="class", data=titanic);

# Define some hatches
hatches = ['-', '+', 'x', '\\', '*', 'o']

# Loop over the bars
for i,thisbar in enumerate(bar.patches):
    # Set a different hatch for each bar
    thisbar.set_hatch(hatches[i])

plt.show()

enter image description here

Thanks to @kxirog in the comments for this additional info:

for i,thisbar in enumerate(bar.patches) will iterate over each colour at a time from left to right, so it will iterate over the left blue bar, then the right blue bar, then the left green bar, etc.

Leave a Comment