2

I have data with the word alpha in it, and I'd like to use ggplot2 to render the alpha in the breaks as the symbol.

df <- data.frame(Method = c("Method (alpha = 0.01)", "Method (alpha = 0.05)"),
                 Value = c(2,3))

ggplot(df, aes(x = Method,
               y = Value)) +
  geom_point()

enter image description here

I couldn't find this on the site, but I don't think it will be that difficult a question. I can get single values in breaks to work using the expression command in ggplot2::xlab, etc., but I can't figure out how to create a vector of expressions. For example, the code

c(expression("Method (alpha = 0.01)"),
+ expression("Method (alpha = 0.05)"))

gives as output

expression("Method (alpha = 0.01)", "Method (alpha = 0.05)")
  • Possible duplicate of [How to use subscripts in ggplot2 legends \[R\]](http://stackoverflow.com/questions/6202667/how-to-use-subscripts-in-ggplot2-legends-r) –  Oct 16 '15 at 04:32
  • 1
    True. My apologies. I do prefer parsing, though. –  Oct 16 '15 at 05:04

1 Answers1

1

You can use parse as in the following possibilities. I think this is easier than having to write out lists of expressions.

Edit

To increase the space between 'Method' and the rest,

df$Method <- gsub("Method", "Method~", as.character(df$Method))

Then, plot

ggplot(df, aes(x = Method, y = Value)) +
  geom_point() +
  scale_x_discrete(labels = parse(text=gsub('=','==',as.character(df$Method))))

or

ggplot(df, aes(x = Method, y = Value)) +
  geom_point() +
  scale_x_discrete(labels = parse(text=paste("alpha", c(0.01, 0.05), sep="==")))

The result from the first one, enter image description here

Rorschach
  • 31,301
  • 5
  • 78
  • 129
  • Brilliant. Apologies for following up a question in a comment, but how do you get a space between "Method" and "(\alpha = 0.01)"? –  Oct 16 '15 at 05:03
  • 1
    No problem, see the dreaded `?plotmath` page for more terrible ways to format expression in R. For the space, do the following prior to the plotting code above. `df$Method <- gsub("Method", "Method~", as.character(df$Method))`. Add more "~" if you want more spaces. – Rorschach Oct 16 '15 at 05:10