Broxy
Broxy

Reputation: 122

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

Upvotes: 1

Views: 49

Answers (1)

Redox
Redox

Reputation: 10017

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

Upvotes: 2

Related Questions