Question

How can I make an x or y label like "$\alpha$ + $\beta$ is my label" in a ggplot2 plot within Rpy2? I've tried getting any greek letter on the plot using r.expression:

p = ggplot2.ggplot(mydata) + r.xlab(r.expression("alpha")) 

but this does not work. How can greek letters get plotted alongside regular text?

Was it helpful?

Solution

R's expression() is taking objects, calls, or expression and returns an expression (that's a way to manipulate unevaluated code). expression("alpha") returns the string "alpha" (like it would if writing in R expression("alpha").

One way to get an expression is to parse a string. Using your example in the question that would be:

from rpy2.rinterface import parse
p = ggplot2.ggplot(mydata) + scale_x_continuous(parse("alpha")) 

Should you want to mix expressions (that is syntactically valid R code) with general text (something that cannot be parsed as code, say using spaces and punctuation) you'll have to use R's paste() in the code to parse (this might seem esoteric, but that's the way one has to do it in R as well):

p = ggplot2.ggplot(mydata) + \
    ggplot2.scale_x_continuous(parse('paste(alpha, " and ", beta)'))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top