Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Change color of part of title in ggplot2

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Any hint on how can I do that?

>Solution :

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))

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading