Search code examples
rggplot2formatlegend-properties

ggplot2: Formatting Legend Categories


I would like to be able to do something like this: https://stackoverflow.com/a/30036603, except with "legend.text" instead of "axis.text.x". Is this possible?

It would be something like this, except it's not currently working (all labs are italicized):

data <- data.frame(labs = c("Oranges", "Apples", "Cucumbers"), counts = c(5, 10, 12))

ggplot(data = data) +
geom_bar(aes(x = labs, y = counts,fill=labs), stat="identity") +
theme(axis.text.x=element_text(face=ifelse(levels(data$labs)=="Cucumbers","plain","italic"))) +
  theme(legend.text=element_text(face=ifelse(levels(data$labs)=="Cucumbers","plain","italic")))

Solution

  • Rather than messing with the theme, you can adjust the scales to draw expressions which can include italic words. For example

    toexpr<-function(x) {
      getfun <- function(x) {
        ifelse(x=="Cucumbers", "plain", "italic")
      }
      as.expression(unname(Map(function(f,v) substitute(f(v), list(f=as.name(f), v=as.character(v))), getfun(x), x)))
    }
    
    ggplot(data = data) +
      geom_bar(aes(x = labs, y = counts,fill=labs), stat="identity") +
      scale_x_discrete(breaks =levels(data$labs), labels = toexpr(levels(data$labs))) +
      scale_fill_discrete(breaks=levels(data$labs), labels = toexpr(levels(data$labs))) + 
      theme(legend.text.align = 0)
    

    enter image description here