Reputation: 173
I'm trying to implement vertical lines on my seaborn boxplot to separate each column, so far I can only seem to add major lines ax.xaxis.grid(True, which='major')
which run through the middle. Here is my code and an image of what I'm trying to achieve. Thanks!
# Custom palette
my_pal = {"Year A": "#e42628", "Year B": "#377db6"}
plt.figure(figsize=(16, 10))
sns.axes_style("whitegrid")
ax = sns.boxplot(x='variable', y="value", hue="Condition", showmeans=True, data=df, palette=my_pal, meanprops={"marker":"s","markerfacecolor":"white", "markeredgecolor":"black"})
plt.ylabel("Temperature (\xb0C)")
#ax.axvline(linewidth=2, color='r')
ax.xaxis.grid(True, which='major')
Upvotes: 1
Views: 2289
Reputation: 80429
You can position the minor xticks as follows and use them for the grid:
from matplotlib import pyplot as plt
from matplotlib.ticker import MultipleLocator
import seaborn as sns
import pandas as pd
import numpy as np
N = 200
df = pd.DataFrame({'variable': np.repeat(list('ABCDEFGHIJ'), N // 10),
'value': np.random.uniform(10, 25, N),
'Condition': np.random.choice(['Year A', 'Year B'], N)})
# Custom palette
my_pal = {"Year A": "#e42628", "Year B": "#377db6"}
plt.figure(figsize=(16, 10))
sns.axes_style("whitegrid")
ax = sns.boxplot(x='variable', y="value", hue="Condition", showmeans=True, data=df, palette=my_pal,
meanprops={"marker": "s", "markerfacecolor": "white", "markeredgecolor": "black"})
plt.ylabel("Temperature (°C)")
ax.xaxis.set_minor_locator(MultipleLocator(0.5))
ax.xaxis.grid(True, which='minor', color='black', lw=2)
plt.show()
Upvotes: 2
Reputation: 169434
The default width of boxplots is 0.5 (or 0.15 x [distance between extreme positions] if that is smaller).
If your width is 0.5 you can do this:
import seaborn as sns, matplotlib.pyplot as plt
tips = sns.load_dataset('tips')
ax = sns.boxplot(x='day',y='total_bill',hue='sex',data=tips)
[ax.axvline(x+.5,color='k') for x in ax.get_xticks()]
plt.show()
Upvotes: 3