ggplot的注释中的文本格式

问题描述

是否可以用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)

enter image description here

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

library(tidyverse)
library(ggtext)

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

enter image description here