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)

1 Answer 1

13

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

Sign up to request clarification or add additional context in comments.

2 Comments

You should use the <br> tag instead of \n to achieve the desired output. @alberson-miranda
Do you know if it is possible to change the fill of only part of the text? I tried doing something like <span style='background-color:#fff'>, but it did not work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.