【问题标题】:How to use Matplotlib rcParams with Seaborn如何在 Seaborn 中使用 Matplotlib rcParams
【发布时间】:2022-12-13 18:28:15
【问题描述】:

我正在为我的公司编写自定义 matplotlib 样式表。除其他事项外,我正在尝试更改箱线图线条的颜色。以下示例使用字典更改 rcParams。使用 matplotlib 构建的标准图具有正确的颜色,而在 seaborn 图中似乎只有一些参数发生了变化。我如何强制 seaborn 使用我的样式表?

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

df_penguins = pd.read_csv(
    "https://raw.githubusercontent.com/mwaskom/seaborn-data/master/penguins.csv"
)
ex = {
        'boxplot.boxprops.color': 'hotpink',
        'boxplot.notch': True,
        'boxplot.patchartist': False,
        'boxplot.showbox': True,
        'boxplot.showcaps': True,
        'boxplot.showfliers': True,
        'boxplot.showmeans': False,
        'boxplot.vertical': True,
        'boxplot.whiskerprops.color': 'hotpink',
        'boxplot.whiskerprops.linestyle': '--',
        'boxplot.whiskerprops.linewidth': 1.0,
        'boxplot.whiskers': 1.5,
    }

plt.rcParams.update(**ex)
fig, (ax1, ax2) = plt.subplots(
    ncols=2, 
    sharey=True,
    figsize=plt.figaspect(0.5)
)
sns.boxplot(data=df_penguins, y="body_mass_g", ax=ax1)

ax2.boxplot(df_penguins.body_mass_g.dropna())
plt.show()

【问题讨论】:

  • 什么是期望的输出?
  • seaborn 箱线图通常不会从 matplotlib rcparams 中读取(否则默认情况下它们看起来不会有什么不同)。

标签: python matplotlib seaborn


【解决方案1】:

不同于@mwaskom 的评论海波恩确实在引擎盖下使用matplotlib's rcParams

默认情况下,您通过 sns.set_theme() 激活 seaborn 默认值,这对 rcParams 有直接影响。您可以使用该函数中的 rc 参数覆盖默认值。

旁注:可以但不建议混合使用 matplotlibseaborn 导入。简而言之:导入seaborn时不要导入matplotlib

我更新了你的代码。

#!/usr/bin/env python3
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

df_penguins = pd.read_csv(
    "https://raw.githubusercontent.com/mwaskom/seaborn-data/master/penguins.csv"
)
ex = {
        'boxplot.boxprops.color': 'hotpink',
        'boxplot.notch': True,
        'boxplot.patchartist': False,
        'boxplot.showbox': True,
        'boxplot.showcaps': True,
        'boxplot.showfliers': True,
        'boxplot.showmeans': False,
        'boxplot.vertical': True,
        'boxplot.whiskerprops.color': 'hotpink',
        'boxplot.whiskerprops.linestyle': '--',
        'boxplot.whiskerprops.linewidth': 1.0,
        'boxplot.whiskers': 1.5,
    }

# This loads the Seaborn default theme settings
# and overwrites them with your values from "ex"
sns.set_theme(rc=ex)

plot = sns.boxplot(data=df_penguins, y="body_mass_g")
plot.figure.show()

请注意,并非来自ex 的所有设置都在这里起作用。例如,hotpink。但我确信这不是我的解决方案的问题。例如 boxplot.notch 确实有效。

所以很抱歉,这只回答了如何通过 Seaborn 修改 rcParams 而不是如何修改主题的特定方面。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-07
    • 2019-10-21
    • 1970-01-01
    • 2021-06-27
    • 1970-01-01
    • 2016-10-10
    • 2017-02-18
    相关资源
    最近更新 更多