8

Is it possible to annotate with html code? I'm trying to color only a few words and not the entire text.

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)

Created on 2020-08-22 by the reprex package (v0.3.0)

Claus Wilke
  • 16,992
  • 7
  • 53
  • 104
Alberson Miranda
  • 1,248
  • 7
  • 25

1 Answers1

11

You can use package 'ggtext'. It is quite new. The only change needed for your example is to replace the geom: using "richtext" instead of "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

It is possible to use fill = NA to remove the background. To remove the border line label.color = NA can be used.

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)

enter image description here

Pedro J. Aphalo
  • 5,796
  • 1
  • 22
  • 23