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

92

我使用seaborn中的factorplot绘制了数据,并获得了facetgrid对象,但仍然不明白如何在这样的图中设置以下属性:

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

3
下面的回答是正确的,并且应该会对您有所帮助,但我想说的是,听起来您正在IPython笔记本中绘图,因此问题实际上与seaborn无关,而是笔记本将图形缩小,如果它们比分配给它们的div大。如果您保存图形,则一切都应该是您期望的大小。 - mwaskom
1
此外,如果您要在列上绘制大量变量而没有行变量,则可以使用 col_wrap 将分面“包装”到多个行中,这可能会有所帮助。 - mwaskom
5个回答

147

您可以通过调用 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))

输入图片描述


大小相对于默认的 matplotlib 字体大小而言。对我来说,更好的方法是在脚本或 Jupyter 笔记本的顶部使用 plt.rc() 调用来更改字体大小。请参见 https://dev59.com/UG865IYBdhLWcg3wR8ah。 - fviktor
7
这似乎覆盖了所选的主题。 - CookieMaster
2
这很糟糕,因为它会完全改变图形布局,而不仅仅是字体。 - SomJura
@SomJura 如果你有固定的图像尺寸,你的选择是:a)调整布局使其适合或b)让它们被图形边界截断。所以不仅是“糟糕”,而且也是“必要”和“实用”的。 - Paul H
1
@PaulH 我同意这个观点。问题实际上是当调用sns.set()时,某些更多的参数会在幕后悄悄地被改变。例如,绘图区域的背景颜色会被更改为 Seaborn 的默认值。@CookieMaster 也提到了类似的问题。 - SomJura

52

FacetGrid绘图会产生非常小的标签。虽然@paul-h已经描述了使用sns.set来改变字体比例的方法,但这可能不是最优解,因为它会改变所有绘图的font_scale设置。

您可以使用seaborn.plotting_context来仅更改当前绘图的设置:

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

29
@mwaskom说:“如果上下文是None,则font_scale被忽略,因此您需要使用plotting_context(“notebook”,font_scale = 5.5)或类似的内容。”(https://dev59.com/u43da4cB1Zd3GeqP5NR4#31865996) - Chris Warth

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()

这是输出内容:

输入图像描述


非常好的创意主意 - undefined

10
对于图例,您可以使用这个。
plt.setp(g._legend.get_title(), fontsize=20)

当你调用制作facetgrid对象的函数后,返回的对象为g。

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”方法错误)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接