【问题标题】:How can I change the font size using seaborn FacetGrid?如何使用 seaborn FacetGrid 更改字体大小?
【发布时间】:2014-10-09 06:47:03
【问题描述】:

我已经在seaborn 中用factorplot 绘制了我的数据并得到facetgrid 对象,但仍然无法理解如何在这样的图中设置以下属性:

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

【问题讨论】:

  • 下面的回答是正确的,应该可以帮助你,但我会说这听起来像你在 IPython 笔记本中绘图,所以这个问题与 seaborn 没有任何关系,而是如果它们最终大于分配给它们的 div,则笔记本会缩小数字。如果你保存图,一切都应该是你期望的大小。
  • 此外,如果您在列上绘制大量变量并且没有行变量,您可以使用col_wrap 将构面“包装”到多行上,这可能会有所帮助。

标签: python seaborn


【解决方案1】:

您可以在对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() 调用来更改字体大小。见stackoverflow.com/questions/3899980/…
  • 这似乎覆盖了所选主题。
  • 这很糟糕,因为它完全改变了图形布局,而不仅仅是字体。
  • @SomJura 如果您有固定的图像尺寸,您的选择是:a)调整布局以使其适合或 b)让它们被图形边界截断。所以不仅仅是“坏的”,还有“必要的”和“实用的”
  • @PaulH 我同意这一点。问题在于,当调用sns.set() 时,在后台默默地更改了更多参数。例如绘图区域的背景颜色更改为 seaborn 默认值。 @CookieMaster 提到了类似的事情。
【解决方案2】:

FacetGrid 情节确实产生了非常小的标签。虽然@paul-h 描述了使用sns.set 作为更改字体缩放的一种方式,但它可能不是最佳解决方案,因为它会更改所有绘图的font_scale 设置。

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

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

【讨论】:

  • @mwaskom 说“如果上下文是None,font_scale 将被忽略,所以你想要plotting_context("notebook", font_scale=5.5) 或类似的。” (stackoverflow.com/a/31865996/1135316)
【解决方案3】:

我对@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()

这是输出:

【讨论】:

    【解决方案4】:

    对于图例,可以用这个

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

    其中 g 是您调用创建它的函数后返回的 facetgrid 对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-15
      • 2016-01-25
      • 1970-01-01
      • 2016-08-03
      • 2018-10-16
      • 2016-09-11
      • 1970-01-01
      相关资源
      最近更新 更多