我正在尝试更改我正在绘制的一系列箱线图中的所有字体元素。我的代码类似于
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
字体大小发生变化,但其他一切都保持不变:
为什么?我该如何解决这个问题?
sns.set
、sns.set_style
和rcParams
的答案有很多。
set_context
和set_style
grid.linewidth
rcParms
已由 seaborn 函数设置。.set
是 .set_theme
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)