How to add vertical grid lines in a grouped boxplot in Seaborn?

Viewed 13938

I want to create a grouped boxplot with vertical grid lines in seaborn, i.e., at each tick, there should be a vertical line, just as in a regular scatter plot.

Some example code:

import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import numpy.random as rnd

some_x=[1,2,3,7,9,10,11,12,15,18]
data_for_each_x=[]

for i in range(0, len(some_x)):
    rand_int=rnd.randint(10,30)
    data_for_each_x.append([np.random.randn(rand_int)])

sns.set()
sns.boxplot(data=data_for_each_x, showfliers=False)
plt.show()

How it looks:

enter image description here

1 Answers

If I understood you correctly, you want the vertical white grid lines instead of the horizontal lines which you are getting currently. This is one way to do so:

Create an axis object ax and then assign this to the sns.boxplot. Then you can choose which grid lines to show by using a boolean argument to ax.xaxis.grid and ax.yaxis.grid. Since you want the vertical grid lines, turn off the y-grid (False) and turn on the x-grid (True).

import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import numpy.random as rnd

fig, ax = plt.subplots() # define the axis object here
some_x=[1,2,3,7,9,10,11,12,15,18]
data_for_each_x=[]

for i in range(0, len(some_x)):
    rand_int=rnd.randint(10,30)
    data_for_each_x.append([np.random.randn(rand_int)])

sns.set()
sns.boxplot(data=data_for_each_x, showfliers=False, ax=ax) # pass the ax object here

ax.yaxis.grid(False) # Hide the horizontal gridlines
ax.xaxis.grid(True) # Show the vertical gridlines

In case you want to show both x and y grids, use ax.grid(True)

enter image description here

Related