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