Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 344
Marcel Avatar asked Dec 21 '18 21:12

Marcel


People also ask

How do you add tiles to Seaborn plot?

To add a title to a single seaborn plot, you can use the . set() function. To add an overall title to a seaborn facet plot, you can use the . suptitle() function.

What is SNS Despine?

The despine() is a function that removes the spines from the right and upper portion of the plot by default. sns. despine(left = True) helps remove the spine from the left.

How do I get rid of gridlines in Seaborn?

Create a data frame using DataFrame wth keys column1 and column2. Use data frame data to plot the data frame. To get rid of gridlines, use grid=False.

Which of the following is the correct syntax to create a box plot using Seaborn?

Syntax: seaborn. boxplot(x, y, hue, data); Python3.


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

like image 110
Sheldore Avatar answered Sep 30 '22 19:09

Sheldore