在 seaborn 图中使用 with sns.set

Using with sns.set in seaborn plots

我已经搜索了一个明确的答案,但没有找到,如果之前有人问过这个问题,我深表歉意。我将 seaborn 0.6 与 matplotlib 1.4.3 一起使用。我想暂时更改绘图的样式,因为我正在 ipython 笔记本中创建许多图形。

具体来说,在这个例子中,我想在每个绘图的基础上同时更改字体大小和背景样式。

这创建了我正在寻找的图,但全局定义了参数:

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

但是失败了:

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__

我也试过:

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

这并没有失败,但是它也没有改变字体的大小。任何帮助将不胜感激。

您可以在 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)

这就是我正在使用的,利用 matplotlib 提供的上下文管理:

import matplotlib

class Stylish(matplotlib.rc_context):
    def __init__(self, **kwargs):
        matplotlib.rc_context.__init__(self)
        sns.set(**kwargs)

然后例如:

with Stylish(font_scale=2):
    sns.kdeplot(x, shade=True)