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

How to italicize select words in a ggplot legend?

I have a stacked bar plot with many bars and there are 15 different categories in the legend. I would like only some words of some categories in the legend to be in italics. I think that the answer here is the basis of how to do this, but I just can’t wrap my head around how to get it to apply to only exactly the words I need to be italics.

Using this example, it would be as if I wanted the words Very and Ideal to be in italics.

ggplot(data = diamonds) + 
  geom_bar(mapping = aes(x = cut, fill = cut))

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

>Solution :

E.g., use gsub to substitute the respective words with "*word*" (using a regex pattern).

library(tidyverse)
library(ggtext)

diamonds %>%
  mutate(cut_fill = gsub("(Very|Ideal)", "\\*\\1\\*", cut)) %>%
ggplot() + 
  geom_bar(mapping = aes(x = cut, fill = cut_fill)) +
  theme(legend.text = element_markdown())

Created on 2023-04-19 with reprex v2.0.2

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