How do I set individual background colours for each xtick

Question:

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

Asked By: Broxy

||

Answers:

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

Answered By: Redox
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.