如何使用 sns.set 和 rcParams 更改所有子图的字体大小

问题描述 投票:0回答:1

我正在尝试更改我正在绘制的一系列箱线图中的所有字体元素。我的代码类似于

from pathlib import Path
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt


def plot_group(df, nrow, ncol, size, plot_title):

    sns.set(style="darkgrid")
    plt.rcParams['font.size'] = size
    fig, axes = plt.subplots(nrow, ncol, figsize=(15, 10), tight_layout=True)
    fig.suptitle(plot_title)
    n_boxplots = 2
    for i in range(nrow):  
        for j in range(ncol): 
            current_ax = axes[i, j]
            sns.boxplot(data=df[['foo','bar']], palette="Set2", ax=current_ax)
            current_ax.set_title("foo", fontsize=18)

    plt.savefig(f'font_size_{size}.png', dpi=75)
    plt.close(fig)

nrow = 3
ncol = 3
rng = np.random.default_rng(0)
arr = rng.random((30, 2))
df = pd.DataFrame(data=arr, columns=['foo', 'bar'])
for size in [14, 22]:

    plot_title = f"Font size = {size}"
    plot_group(df, nrow, ncol, size, plot_title)

然而,这会导致两个数字,其中只有

suptitle
字体大小发生变化,但其他一切都保持不变:

为什么?我该如何解决这个问题?

python matplotlib seaborn font-size subplot
1个回答
0
投票
  • 关于
    sns.set
    sns.set_style
    rcParams
    的答案有很多。
  • 如 seaborn rcmod.py 文件所示,
    rcParms
    已由 seaborn 函数设置。
  • .set
    .set_theme
  • 的别名
  • Override
    rcParams
    set by
    .set_theme
    using the parameters as defined here.
  • 对于这段代码,删除
    sns.set(style="darkgrid")
    plt.rcParams['font.size'] = size
    ,并使用
    sns.set_theme(context={'font.size': size})
    代替。
    • 直接用
      rcParams
      ,用
      sns.set_theme
      的时候,好像不行。
  • python 3.11.2
    matplotlib 3.7.1
    seaborn 0.12.2
  • 中测试
def plot_group(df, nrow, ncol, size, plot_title):

    sns.set_theme(context={'font.size': size})  # use set_theme
    
    fig, axes = plt.subplots(nrow, ncol, figsize=(15, 10))
    axes = axes.flat
    fig.suptitle(plot_title)
    for ax in axes:
        sns.boxplot(data=df, palette="Set2", ax=ax)
        ax.set_title("foo", fontsize=18)

    plt.savefig(f'font_size_{size}.png', dpi=75)
    plt.close(fig)


nrow = 3
ncol = 3
rng = np.random.default_rng(0)
arr = rng.random((30, 2))
df = pd.DataFrame(data=arr, columns=['foo', 'bar'])
for size in [14, 22]:
    plot_title = f"Font size = {size}"
    plot_group(df, nrow, ncol, size, plot_title)

© www.soinside.com 2019 - 2024. All rights reserved.