Change color of part of title in ggplot2 [duplicate]

I'm struggling on how can I make a plot using two colors in the tittle. I need to use part of the title in "red" and the other part in "black".

I just wrote a toy example to facilitate the explanation:

library("tidyverse")

iris %>% 
  ggplot() +
  geom_point(aes(x= Sepal.Length, y = Sepal.Width)) +
  labs(title = "First part in black, this second part in red")
  theme(plot.title = element_text(hjust = 0.5,face="bold", size = 17))

enter image description here

Any hint on how can I do that?


Solution 1:

One option would be the ggtext package which allows for styling text via HTML, CSS and markdown. To this end you have to replace element_text by element_markdown and add your desired styling to your title string via HTML and CSS:

library(ggplot2)
library(ggtext)
ggplot(iris) +
  geom_point(aes(x= Sepal.Length, y = Sepal.Width)) +
  labs(title = "First part in black, <span style='color: red;'>this second part in red<span>") + 
  theme(plot.title = element_markdown(hjust = 0.5,face="bold", size = 17))