1

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))
adelebb
  • 13
  • 2

1 Answers1

0

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

The opposite, italicising all and leaving just a few words regular, is more complex and the complexity of its solution will hugely depend on the position of the "non-italics" words which you expect. In particular, would they always be the first or last word, or always in the middle, or both. In the example below, I assume a position always at the beginning and am using an optional capture group.

diamonds %>%
  ## due to if else factor behaviour 
  ## see also: https://stackoverflow.com/questions/6668963/how-to-prevent-ifelse-from-turning-date-objects-into-numeric-objects
  mutate(cut_fill = ifelse(grepl("Ideal", cut), as.character(cut), as.character(gsub("(Very )?(.*)", "\\1\\*\\2\\*", 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

tjebo
  • 21,977
  • 7
  • 58
  • 94
  • Thanks so much!Do you know if there is a good short cut for opposite scenario in which most words in a long legend should be italicized and only a few should be in plain text? – adelebb Apr 19 '23 at 13:48
  • @adelebb I think this is a different enough situation that it might warrant another question. If so, please don't forget to link to this here and explain the differences, and also specify the conditions where the plain text words would be located. (it might require a different example plot) – tjebo Apr 19 '23 at 14:10
  • @adelebb updating my answer once more. I don't think you need to ask a new question. Keep your eyes peeled - I'll be asking a question regarding the regex in a few minutes which will make the code slightly simpler – tjebo Apr 19 '23 at 14:24
  • @adelebb check https://stackoverflow.com/questions/76055755/conditional-replacement-of-optional-group-with-gsub/76055974#76055974 - this might help you with your quest! – tjebo Apr 19 '23 at 15:17