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!
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.
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.
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.
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()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With