ggplot 注释中的文本格式

Text formatting in ggplot's annotate

是否可以用html代码进行注释?我试图只给几个词上色,而不是给整个文本上色。

library(tidyverse)
#> Warning: package 'ggplot2' was built under R version 4.0.2

mtcars %>%
  ggplot(aes(x = hp, y = mpg)) +
  geom_point() +
  annotate(geom = "text", label = "I'm <span style='color: red;'>red</span> \n and i'm <span style='color: orange;'>orange</span>",
           x = 250, y = 25)

reprex package (v0.3.0)

于 2020-08-22 创建

您可以使用包 'ggtext'。这是很新的。您的示例所需的唯一更改是替换 geom:使用 "richtext" 而不是 "text".

library(tidyverse)
library(ggtext)
#> Warning: package 'ggplot2' was built under R version 4.0.2

mtcars %>%
  ggplot(aes(x = hp, y = mpg)) +
  geom_point() +
  annotate(geom = "richtext", label = "I'm <span style='color: red;'>red</span> \n and i'm <span style='color: orange;'>orange</span>",
           x = 250, y = 25)

可以使用fill = NA删除背景。要删除边框线,可以使用 label.color = NA

library(tidyverse)
library(ggtext)

mtcars %>%
  ggplot(aes(x = hp, y = mpg)) +
  geom_point() +
  annotate(geom = "richtext", label = "I'm <span style='color: red;'>red</span>\n and i'm <span style='color: orange;'>orange</span>",
           x = 250, y = 25, fill = NA, label.color = NA)