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

How do I set individual background colours for each xtick

I have the code below to create a swarm plot using seaborn.

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
data = {'Days': np.full((48, 5), [6, 7, 8, 9, 10]).reshape(-1),
        'Group': np.full((80, 3), ["Group1", "Group2", "Group3"]).reshape(-1), 
        'Value': np.random.rand(240)}
df = pd.DataFrame(data=data)
fig, ax = plt.subplots(figsize=(20, 10), dpi=80)
sns.stripplot(x=df.Days, y=df.Value, jitter=0, size=5, ax=ax, linewidth=1,
              dodge=True, hue=df.Group, palette="Set1", data=df)
plt.show()

How can I change the background colour of the individual groups, int this case the different Days? So Day 4 has a grey Background, Day 7 a white, Day 8 grey again and so on? See in the image below.
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 use axvspan() to do this. Below is the updated code. This will set every alternate xtick range as gray or white..

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
data = {'Days': np.full((48, 5), [6, 7, 8, 9, 10]).reshape(-1),
        'Group': np.full((80, 3), ["Group1", "Group2", "Group3"]).reshape(-1), 
        'Value': np.random.rand(240)}
df = pd.DataFrame(data=data)
fig, ax = plt.subplots(figsize=(20, 10), dpi=80)
sns.stripplot(x=df.Days, y=df.Value, jitter=0, size=5, ax=ax, linewidth=1,
              dodge=True, hue=df.Group, palette="Set1", data=df)
for i in range(6):
    if i%2 == 0:
        plt.axvspan(i-0.5, i+.5, facecolor='gray', alpha=0.3)
plt.show()

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