关于python:Seaborn配置隐藏默认的matplotlib

Seaborn configuration hides default matplotlib

本问题已经有最佳答案,请猛点这里访问。

Seaborn提供了一些图形,这些图形对于科学数据表示非常有趣。
因此,我开始使用这些Seaborn图形以及其他自定义的matplotlib图。
问题是一旦我这样做:

1
import seaborn as sb

此导入似乎为全局设置了seaborn的图形参数,然后该导入下方的所有matplotlib图形都获得了seaborn参数(它们具有灰色背景,linewithd更改等)。

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


如果您永远不想使用seaborn样式,但是想要一些seaborn函数,则可以使用以下行(文档)导入seaborn:

1
import seaborn.apionly as sns

如果要在同一脚本中以seaborn样式生成一些图,而以seaborn样式生成一些图,则可以使用seaborn.reset_orig函数关闭seaborn样式。

看来,执行apionly导入实际上会在导入时自动设置reset_orig,因此,这取决于您,这在您的用例中最有用。

这是在matplotlib默认值和seaborn之间切换的示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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')

生成以下三个图:

seaborn-off.png:
seaborn-off

seaborn-on.png:
seaborn-on

seaborn-offagain.png:
enter image description here


从seaborn版本0.8(2017年7月)开始,图形样式在导入时不再更改:

The default [seaborn] style is no longer applied when seaborn is imported. It is now necessary to explicitly call set() or one or more of set_style(), set_context(), and set_palette(). Correspondingly, the seaborn.apionly module has been deprecated.

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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)

阅读有关plt.style()的更多信息。


seaborn.reset_orig()函数允许将所有RC参数恢复为原始设置(尊重自定义rc)


您可以按照样式指南中的说明使用matplotlib.style.context功能。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#%matplotlib inline #if used in jupyter notebook
import matplotlib.pyplot as plt
import seaborn as sns

# 1st plot
with plt.style.context("seaborn-dark"):
    fig, ax = plt.subplots()
    ax.plot([1,2,3], label="First plot (seaborn-dark)")

# 2nd plot
with plt.style.context("default"):
    fig, ax = plt.subplots()
    ax.plot([3,2,1], label="Second plot (matplotlib default)")

#  3rd plot
with plt.style.context("seaborn-darkgrid"):
    fig, ax = plt.subplots()
    ax.plot([2,3,1], label="Third plot (seaborn-darkgrid)")

enter image description here


正如在另一个问题中所解释的,您可以使用以下方式导入seaborn:

1
import seaborn.apionly as sns

而且matplotlib样式不会被修改。