如何让geom_text继承主题规范? (ggplot2)

12
在ggplot2中,是否有一种优雅的方式可以使geom_text/geom_label继承theme中的规范,例如base_family?
或者换句话说:我能否指定一个也适用于geom_text/geom_label的主题?
示例: 我希望文本/标签看起来与主题中指定的axis.text完全相同... 显然,我可以手动将规范添加为可选参数到geom_text中,但是我希望它能"自动"继承规范...
library("ggplot2")

ggplot(mtcars, aes(x = mpg,
                   y = hp,
                   label = row.names(mtcars))) +
  geom_point() +
  geom_text() +
  theme_minimal(base_family = "Courier")

<code>theme</code>规格未继承

补充说明:如果能够同时适用于ggrepel :: geom_text_repel / geom_label_repel的解决方案将是完美的...


theme 只影响图表的非数据方面。您可以查看 update_geom_defaults在 SO 上的示例)。 - Henrik
1个回答

17

你可以

设置整体字体

首先,根据您所使用的系统,您需要检查可用的字体。由于我正在使用Windows,因此我正在使用以下字体:

install.packages("extrafont")
library(extrafont)
windowsFonts() # check which fonts are available

theme_set函数可以让您指定ggplot的整体主题。因此,theme_set(theme_minimal(base_family = "Times New Roman"))可以定义图形的字体。

继承字体以使标签与图形匹配

为了使标签继承此文本,我们需要使用两个东西:

  1. update_geom_defaults可以更新ggplot中未来绘图的几何对象样式:http://ggplot2.tidyverse.org/reference/update_defaults.html
  2. theme_get()$text$family提取当前全局ggplot主题的字体。

通过将这两个组合起来,可以更新标签样式,如下所示:

# Change the settings
update_geom_defaults("text", list(colour = "grey20", family = theme_get()$text$family))
update_geom_defaults("text_repel", list(colour = "grey20", family = theme_get()$text$family))

结果

theme_set(theme_minimal(base_family = "Times New Roman"))

# Change the settings
update_geom_defaults("text", list(colour = "grey20", family = theme_get()$text$family))

# Basic Plot
ggplot(mtcars, aes(x = mpg,
                   y = hp,
                   label = row.names(mtcars))) +
  geom_point() +
  geom_text()

输入图像描述

# works with ggrepel
update_geom_defaults("text_repel", list(colour = "grey20", family = theme_get()$text$family))

library(ggrepel)

ggplot(mtcars, aes(x = mpg,
                   y = hp,
                   label = row.names(mtcars))) +
  geom_point() +
  geom_text_repel()

输入图像描述


1
很好的答案,阐述得很清晰 - chamaoskurumi

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