Search code examples
rggplot2ggtext

Text formatting in ggplot's annotate


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)


Solution

  • 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