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

gos*_*osz 5 themes r ggplot2 ggrepel

是否有一种优雅的方式ggplot2来制作geom_text/ geom_label继承themebase_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")
Run Code Online (Sandbox Code Playgroud)

<code>ggrepel::geom_text_repel/geom_label_repel</code>将是完美的......</p></p>
    </div>
  </div>

<div class=

Mic*_*per 6

您可以

设置整体字体

首先,根据系统,您需要检查哪些字体可用.当我在Windows上运行时,我使用以下内容:

install.packages("extrafont")
library(extrafont)
windowsFonts() # check which fonts are available
Run Code Online (Sandbox Code Playgroud)

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))
Run Code Online (Sandbox Code Playgroud)

结果

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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

# 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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述