Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding hatch to Seaborn multi-boxplot

In the chart below, I want to add hatch (‘/’) only to the ‘rest’ category in both boxlots. I will be glad if you help

I add the sample codes below:

import seaborn as sns
exercise = sns.load_dataset("exercise")

df1=exercise.loc[(exercise["diet"]=="low fat"),:]
df2=exercise.loc[(exercise["diet"]=="no fat"),:]

fig, axes = plt.subplots(1, 2)
ax1=sns.boxplot(x='kind', y='pulse', orient='v', ax=axes[0],data=df1, showfliers=False)
ax2= sns.boxplot(x='kind', y='pulse', orient='v', ax=axes[1],data=df2, showfliers=False)

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can iterate over the xticks labels and patches and set the hatch for rest only:

import seaborn as sns
import matplotlib.pyplot as plt

exercise = sns.load_dataset("exercise")

df1=exercise.loc[(exercise["diet"]=="low fat"),:]
df2=exercise.loc[(exercise["diet"]=="no fat"),:]

fig, axes = plt.subplots(1, 2)
sns.boxplot(x='kind', y='pulse', orient='v', ax=axes[0],data=df1, showfliers=False)
sns.boxplot(x='kind', y='pulse', orient='v', ax=axes[1],data=df2, showfliers=False)

for ax in axes.flatten():
    for lbl, patch in zip(ax.get_xticklabels() , ax.patches):
        if lbl.get_text() == 'rest':
            patch.set_hatch('/')
            patch.set_edgecolor(patch.get_facecolor())
            patch.set_facecolor('none')

plt.show()

Output:

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading