johnchase johnchase - 2 years ago 387
Python Question

Using with sns.set in seaborn plots

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);


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.

Answer Source

The best thing to do would be to combine the seaborn style and context parameters into one dictionary and then pass it to the plt.rc_context function:

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt  
x = np.random.normal(size=100)
with plt.rc_context(dict(sns.axes_style("whitegrid"),
                         **sns.plotting_context("notebook", font_scale=1.5))):
    sns.kdeplot(x, shade=True)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download