7

I'm trying to get a superscript for units of my y-axis using plotmath expressions referenced in several posts. I've looked through threads on using expression and also here, but it just isn't working for me. Here's what I have so far:

ggplot(data.frame, aes(Region, Zmar_sh)) + 
  geom_boxplot() + xlab("Region") +  
  ylab(expression(paste("eelgrass shoot density", " (shoots/", expression(m[2])))) +
  ggtitle(expression(paste(italic("Zostera marina")," shoot density in X Bay", sep = " ")))

The ggtitle expression works, but I'm still not getting my y axis to read "eelgrass shoot density (shoots/m2)" with the "2" as superscript. What am I missing?

1 Answer 1

8

You don't need the second expression(). Also, m[2] gives a subscript. Use m^2 for a superscript.

Here's an example with the built-in mtcars data frame:

ggplot(mtcars, aes(wt, mpg)) +
  geom_point() +
  ylab(expression(paste("eelgrass shoot density", " (shoots/", m^2,")")))

In fact, you don't even need to use paste. Instead you could do this:

ylab(expression(eelgrass~shoot~density~(shoots/m^2)))

where ~ is the "space" character. If you put actual spaces between the words (without using ~), you'll get an error. However, for readability, you can also do this:

ylab(expression(eelgrass ~ shoot ~ density ~ (shoots/m^2)))

which is equivalent to the code above, because the spaces are ignored as long as the ~ is there.

Any of the ylab expressions above will give the following plot:

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I wasn't aware of this use of the ~. I knew it was something small that I was missing. And you were right about the superscript, of course. I am also working with subscripts in my code and wrote the incorrect term in my rush to post.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.