如何使用seaborn的FacetGrid更改字体大小?

93 投票
5 回答
212587 浏览
提问于 2025-04-18 17:24

我用 seabornfactorplot 绘制了我的数据,得到了一个 facetgrid 对象,但我还是不太明白在这样的图表中,以下这些属性该怎么设置:

  1. 图例大小:当我绘制很多变量时,图例变得很小,字体也很小。
  2. y轴和x轴标签的字体大小(和上面的问题类似)

5 个回答

2

这个方法对我有效

g = sns.catplot(x="X Axis", hue="Class", kind="count", legend=False, data=df, height=5, aspect=7/4)
g.ax.set_xlabel("",fontsize=30)
g.ax.set_ylabel("Count",fontsize=20)
g.ax.tick_params(labelsize=15)

但是直接在 g 上调用 set_xlabel 是不行的,比如用 g.set_xlabel(),这样会出现“Facetgrid 没有 set_xlabel 方法”的错误

10

关于图例,你可以使用这个

plt.setp(g._legend.get_title(), fontsize=20)

这里的 g 是你在调用创建它的函数后得到的一个叫 facetgrid 的对象。

18

我对@paul-H的代码做了一些修改,现在你可以单独设置x轴、y轴和图例的字体大小了:

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
x = np.random.normal(size=37)
y = np.random.lognormal(size=37)

# defaults                                                                                                         
sns.set()
fig, ax = plt.subplots()
ax.plot(x, y, marker='s', linestyle='none', label='small')
ax.legend(loc='upper left', fontsize=20,bbox_to_anchor=(0, 1.1))
ax.set_xlabel('X_axi',fontsize=20);
ax.set_ylabel('Y_axis',fontsize=20);

plt.show()

这是输出的效果:

在这里输入图片描述

52

FacetGrid图的标签确实比较小。虽然@paul-h提到可以用sns.set来调整字体大小,但这可能不是最好的办法,因为这样会影响到所有图的font_scale设置。

你可以使用seaborn.plotting_context来只改变当前图的设置:

with sns.plotting_context(font_scale=1.5):
    sns.factorplot(x, y ...)
148

你可以在调用 sns.set() 时放大字体。

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
x = np.random.normal(size=37)
y = np.random.lognormal(size=37)

# defaults
sns.set()
fig, ax = plt.subplots()
ax.plot(x, y, marker='s', linestyle='none', label='small')
ax.legend(loc='upper left', bbox_to_anchor=(0, 1.1))

在这里输入图片描述

sns.set(font_scale=5)  # crazy big
fig, ax = plt.subplots()
ax.plot(x, y, marker='s', linestyle='none', label='big')
ax.legend(loc='upper left', bbox_to_anchor=(0, 1.3))

在这里输入图片描述

撰写回答