stefano-meschiari / latex2exp

Use LaTeX in R graphics.
Other
186 stars 10 forks source link

ggplot axis tick labels #1

Closed mdgbeck closed 9 years ago

mdgbeck commented 9 years ago

I'm running into a problem when trying to use the script to label the tick marks using ggplot. There is no error or warning message and the code runs fine, but it leaves the labels blank. Using your example from ggplot graphics, I've edited it to show the problem.

library(plyr) x <- seq(0, 4, length.out=100) alpha <- 1:5 data <- mdply(alpha, function(a, x) data.frame(v=a*x^a, x=x), x)

p <- ggplot(data, aes(x=x, y=v, color=X1)) + geom_line() + coord_cartesian(ylim=c(-1, 10)) + guides(color=guide_legend(title=NULL)) + scale_color_discrete(labels=lapply(c("\alpha", "\beta", "\gamma", "\delta", "\epsilon"), latex2exp)) + scale_x_continuous(labels=lapply(c("\alpha", "\beta", "\gamma", "\delta", "\epsilon"), latex2exp))

print(p)

image

stefano-meschiari commented 9 years ago

You need to use sapply() on the labels argument of scale_x_continuous(). For scale_color_discrete, I'm using lapply to create a correspondence between values of alpha and the list of expressions (each value of alpha is an index into the list returned by lapply). My guess is that this is due to differences in how _discrete and _continuous scales interpret the labels argument (see http://docs.ggplot2.org/current/continuous_scale.html and http://docs.ggplot2.org/current/discrete_scale.html).

Using

p <- ggplot(data, aes(x=x, y=v, color=X1)) +
    geom_line() + 
    coord_cartesian(ylim=c(-1, 10)) +
    guides(color=guide_legend(title=NULL)) +
    scale_color_discrete(labels=lapply(c("\\alpha", "\\beta", "\\gamma", "\\delta", "\\epsilon"), latex2exp)) +
    scale_x_continuous(labels=sapply(c("\\alpha", "\\beta", "\\gamma", "\\delta", "\\epsilon"), latex2exp))

produces the correct plot on the latest ggplot2 release.

If you find this behavior surprising, then you should file a bug with ggplot2.