Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

ax = sns.barplot(x="size", y="algorithm", hue="ordering", data=df2, palette=sns.color_palette("cubehelix", 4))

After (or before) creating a seaborn barplot, is there a way for me to pass in hatch (fill in patterns along with the colors) values for each bar? A way to do this in seaborn or matplotlib would help a lot!

like image 594
kxirog Avatar asked Feb 17 '16 20:02

kxirog


People also ask

How do you plot multiple bar graphs in Seaborn?

We can make multiple columns of the barplot by using the seaborn function group bar. The groupby() method in Pandas is used to divide data into groups depending on specified criteria. In the following example script, we have included the matplotlib library and seaborn module for plotting multiple columns using barplot.

How do you stack bars in Seaborn?

A stacked Bar plot is a kind of bar graph in which each bar is visually divided into sub bars to represent multiple column data at once. To plot the Stacked Bar plot we need to specify stacked=True in the plot method. We can also pass the list of colors as we needed to color each sub bar in a bar.

How do I add values to my barplot in Seaborn?

In seaborn barplot with bar, values can be plotted using sns. barplot() function and the sub-method containers returned by sns. barplot(). Import pandas, numpy, and seaborn packages.


1 Answers

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.

like image 102
tmdavison Avatar answered Sep 21 '22 09:09

tmdavison