在seaborn plots中与sns.set一起使用

2024-05-19 02:25:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经寻找了一个明确的答案,但还没有找到,我很抱歉,如果这是以前问过。我用的是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);

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


Tags: importtrue绘图styleaswithipythonseaborn
2条回答

这就是我使用的,利用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)

最好的做法是将seaborn样式和上下文参数组合到一个字典中,然后将其传递给plt.rc_context函数:

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)

相关问题 更多 >

    热门问题