10

有没有一种优雅的方式ggplot2来制作geom_text/geom_label继承theme规范,比如 a base_family

或者反过来问:我可以指定一个theme也适用于geom_text/geom_label吗?


例子:

我希望text/labels看起来与...axis.text中指定的完全一样theme

显然我可以手动添加规范作为可选参数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将是完美的......

4

1 回答 1

14

你可以

设置整体字体

首先,根据系统,您需要检查哪些字体可用。当我在 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()

在此处输入图像描述

于 2018-02-25T21:01:02.847 回答