Search code examples
rggplot2formattinglegendsuperscript

ggplot legend title: superscript messes up formatting


as you can see (see image below), the superscript in my legend title is moved all the way to the right (probably due to the long word in the first line). First I assumed changing the line height of the title would help, but it didn't. Also I want to have have the line break in order to save space.

Do you have any ideas how to fix this?

library("ggplot2")
x <- seq(1,10,1)
y <- sin(x)
z <- c("1", "1", "2", "2", "2", "1", "2", "3", "3", "3")

df <- data.frame(x,y,z)

p <- ggplot(df, aes(x,y, color=z))
p + geom_point() +
  labs(
    color = expression(
      paste(
        "Catalyst Loading \n(mg cm"^{-2}*")"
        )
      )
    )

enter image description here


Solution

  • It's the \n that messes you legend title. To work with line breaks and expressions I would suggest atop solution:

    library(ggplot2)
    nameColor <- bquote(atop(Catalyst~Loading~phantom(),
                             (mg~cm^-2)))
    ggplot(df, aes(x, y, color = z)) + 
        geom_point() +
        labs(color = nameColor)
    

    enter image description here