Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using with sns.set in seaborn plots

Tags:

python

seaborn

I have searched for a clear answer to this and have not been able to find one, I apologize if this has been asked previously. I'm using seaborn 0.6 with matplotlib 1.4.3. I would like to temporarily change the styles of plots as I am creating many figures in an ipython notebook.

Specifically, in this example, I would like to change both the font size and the background style on a per-plot basis.

This creates the plot I am looking for but defines parameters globally:

import seaborn as sns
import numpy as np

x = np.random.normal(size=100)

sns.set(style="whitegrid", font_scale=1.5)
sns.kdeplot(x, shade=True);

however this fails:

with sns.set(style="whitegrid", font_scale=1.5):
    sns.kdeplot(x, shade=True);

with:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-10-70c5b03f9aa8> in <module>()
----> 1 with sns.set(style="whitegrid", font_scale=1.5):
      2     sns.kdeplot(x, shade=True);

AttributeError: __exit__

I also tried:

with sns.axes_style(style="whitegrid", rc={'font.size':10}):
    sns.kdeplot(x, shade=True);

Which does not fail, however it also does not change the size of the font. Any help would be much appreciated.

like image 235
johnchase Avatar asked Jul 02 '15 17:07

johnchase


People also ask

What is SNS set () in Python?

sns.set() You can also customize seaborn theme or use one of six variations of the default theme. Which are called deep, muted, pastel, bright, dark, and colorblind. # Plot color palette.

How do you set up Darkgrid in seaborn plots?

Set the background to be darkgrid: Darkgrid appear on the sides of the plot on setting it as set_style('darkgrid'). palette attribute is used to set the color of the bars. It helps to distinguish between chunks of data.

How do you plot multiple variables in 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 Xticks in seaborn?

set_yticks() functions in axes module of matplotlib library are used to Set the ticks with a list of ticks on X-axis and Y-axis respectively. Parameters: ticks: This parameter is the list of x-axis/y-axis tick locations. minor: This parameter is used whether set major ticks or to set minor ticks.


1 Answers

You can stack context managers in Python:

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt  
x = np.random.normal(size=100)
with sns.axes_style("whitegrid"), sns.plotting_context("notebook", font_scale=1.5):
    sns.kdeplot(x, shade=True)
like image 97
mwaskom Avatar answered Sep 20 '22 18:09

mwaskom