Seaborn配置隐藏了默认的matplotlib

joa*_*uin 19 python matplotlib seaborn

Seaborn提供了一些非常有趣的科学数据表示图形.因此,我开始使用这些Seaborn图形穿插其他定制的matplotlib图.问题是,一旦我这样做:

import seaborn as sb
Run Code Online (Sandbox Code Playgroud)

这个导入似乎设置了seaborn全局的图形参数,然后导入下面的所有matplotlib图形都获得了seaborn参数(它们得到灰色背景,linewithd更改等等).

在SO中有一个答案解释如何使用matplotlib配置生成seaborn图,但我想要的是在将两个库一起使用时保持matplotlib配置参数不变,同时能够在需要时生成原始的seaborn图.

tmd*_*son 20

如果您从不想使用该seaborn样式,但确实需要一些seaborn功能,可以使用以下行(文档)导入seaborn :

import seaborn.apionly as sns
Run Code Online (Sandbox Code Playgroud)

如果您想要生成一些具有seaborn样式的图形而一些没有,在同一个脚本中,您可以seaborn使用该seaborn.reset_orig函数关闭样式.

看起来apionly导入基本上是reset_orig在导入时自动设置的,所以它取决于你在你的用例中最有用.

以下是在matplotlib默认值之间切换的示例seaborn:

import matplotlib.pyplot as plt
import matplotlib
import numpy as np

# a simple plot function we can reuse (taken from the seaborn tutorial)
def sinplot(flip=1):
    x = np.linspace(0, 14, 100)
    for i in range(1, 7):
        plt.plot(x, np.sin(x + i * .5) * (7 - i) * flip)

sinplot()

# this will have the matplotlib defaults
plt.savefig('seaborn-off.png')
plt.clf()

# now import seaborn
import seaborn as sns

sinplot()

# this will have the seaborn style
plt.savefig('seaborn-on.png')
plt.clf()

# reset rc params to defaults
sns.reset_orig()

sinplot()

# this should look the same as the first plot (seaborn-off.png)
plt.savefig('seaborn-offagain.png')
Run Code Online (Sandbox Code Playgroud)

产生以下三个图:

seaborn-off.png: seaborn关闭

seaborn-on.png: seaborn上

seaborn-offagain.png: 在此输入图像描述

  • 也许最好分享一些代码,以便其他人可以重现这个问题? (2认同)

Fra*_*ues 8

从seaborn版本0.8(2017年7月)开始,图表样式在导入时不再更改.OP愿望现在是默认行为.来自https://seaborn.pydata.org/whatsnew.html:

导入seaborn时,不再应用默认(seaborn)样式.现在需要显式调用set()或set_style(),set_context()和set_palette()中的一个或多个.相应地,seaborn.apionly模块已被弃用.

您可以使用plt.style.use()选择任何绘图的样式.

import matplotlib.pyplot as plt
import seaborn as sns

plt.style.use('seaborn')     # switch to seaborn style
# plot code
# ...

plt.style.use('default')     # switches back to matplotlib style
# plot code
# ...


# to see all available styles
print(plt.style.available)
Run Code Online (Sandbox Code Playgroud)

更多关于plt.style()的信息