Issue
I want add the repeated hatch patterns over a seaborn barplot.
Of course, I checked the below Q&A, but I cannot solve my question.
Is it possible to add hatches to each individual bar in seaborn.barplot?
In the above Q&A, the different patch patterns are applied to the left blue ('-') and the right blue ('+'). I want apply the same patch pattern to the same color bar; ("//") should be applied on the two blue bar, ("\\") should be applied on the two green bar, and ("|") should be applied on the two red bar.
I tried the below code, but I can not realize my ideal figure.
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);
hatches = cycle([ "//" , "\\\\" , "|"])
# 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()
Solution
sns.barplot
returns the matplotlib ax
on which the bar plot has been created. (Giving the return value a very different name can be confusing when searching the seaborn and matplotlib documentation for how to make adjustments.)
ax.patches
indeed contains all the bars. First come all bars of First Class, then all bars of Second Class, then those of Third class. This grouping can be found in ax.containers
which has 3 containers: one for each group of bars. Iterating through these containers helps to hatch each group individually. Later, the legend needs to be created again to also show the hatching.
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(style="whitegrid", color_codes=True)
titanic = sns.load_dataset("titanic")
ax = sns.barplot(x="sex", y="survived", hue="class", data=titanic)
hatches = ["//", "\\\\", "|"]
# Loop over the bars
for bars, hatch in zip(ax.containers, hatches):
# Set a different hatch for each group of bars
for bar in bars:
bar.set_hatch(hatch)
# create the legend again to show the new hatching
ax.legend(title='Class')
plt.show()
Answered By - JohanC
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.