Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add grid lines to a catplot in seaborn?

How can I add grid lines (vertically and horizontally) to a seaborn catplot? I found a possibility to do that on a boxplot, but I have multiple facets and therefore need a catplot instead. And in contrast to this other answer, catplot does not allow an ax argument.

This code is borrowed from here.

import seaborn as sns
sns.set(style="ticks")
exercise = sns.load_dataset("exercise")
g = sns.catplot(x="time", y="pulse", hue="kind", data=exercise)
plt.show()

Any ideas? Thank you!

EDIT: The provided answer is working, but for faceted plots, only the last plot inherits the grid.

import seaborn as sns
sns.set(style="ticks")
exercise = sns.load_dataset("exercise")
g = sns.catplot(x="time", y="pulse", hue="kind", col="diet", data=exercise)
plt.grid()
plt.show()

Can someone explain to me why and how to fix it?

like image 268
Revan Avatar asked Apr 29 '20 13:04

Revan


People also ask

How do you set the white grid in seaborn?

Set the background to be Whitegrid: Whitegrid appears on the sides of the plot on setting it as set_style('whitegrid'). palette attribute is used to set the color of the bars.

How do you plot multiple charts in a grid using Matplotlib and seaborn?

In Seaborn, we will plot multiple graphs in a single window in two ways. First with the help of Facetgrid() function and other by implicit with the help of matplotlib. data: Tidy dataframe where each column is a variable and each row is an observation.

How do you set the dark grid in seaborn plots?

Seaborn has five built-in themes to style its plots: darkgrid , whitegrid , dark , white , and ticks . Seaborn defaults to using the darkgrid theme for its plots, but you can change this styling to better suit your presentation needs. To use any of the preset themes pass the name of it to sns. set_style() .


1 Answers

You can set the grid over seaborn plots in two ways:

1. plt.grid() method:

You need to use the grid method inside matplotlib.pyplot. You can do that like so:

import seaborn as sns
import matplotlib.pyplot as plt

sns.set(style="ticks")
exercise = sns.load_dataset("exercise")
g = sns.catplot(x="time", y="pulse", hue="kind", data=exercise)
plt.grid()  #just add this
plt.show()

Which results in this graph: enter image description here

2. sns.set_style() method

You can also use sns.set_style which will enable grid over all subplots in any given FacetGrid. You can do that like so:

import seaborn as sns
import matplotlib.pyplot as plt


sns.set(style="ticks")
exercise = sns.load_dataset("exercise")
sns.set_style("darkgrid")
g = sns.catplot(x="time", y="pulse", hue="kind", col="diet", data=exercise)
plt.show()

Which returns this graph: enter image description here

like image 166
Anwarvic Avatar answered Sep 22 '22 19:09

Anwarvic