How can I get formatted fractions as axis labels?

1,845 views
Skip to first unread message

Brian Danielak

unread,
Feb 22, 2014, 9:45:37 PM2/22/14
to ggp...@googlegroups.com
# The background


What I'd like to do is replace the current x-axis labels (which are currently powers of two) with pretty math versions of the corresponding fractions. 

So, the desired mapping would have labels like (1/4, 1/2, 1) instead of (2^-2, 2^-1, 1) respectively, but the current log-base-2 scale should be preserved. 

Any help is greatly appreciated. Thanks! And if anything's unclear, please let me know.

- Brian

Dennis Murphy

unread,
Feb 22, 2014, 10:08:18 PM2/22/14
to Brian Danielak, ggplot2
The brute force way to do it is to define the labels manually:

library(ggplot2)
library(scales)

# Toy example:
DF <- data.frame(x = runif(100, 0.1, 10), y = rnorm(100))

ggplot(DF, aes(x = x, y = y)) + geom_point() +
scale_x_continuous(trans = log2_trans(),
breaks = 2^(-3:3),
labels = c("1/8", "1/4", "1/2", "1", "2", "4", "8"))

I don't see how you could switch math_format() in midstream and get it
to work (it may - I just don't see it). I tried an if-else
construction and an ifelse() construction for the labels argument but
neither worked for me.

Dennis
> --
> --
> You received this message because you are subscribed to the ggplot2 mailing
> list.
> Please provide a reproducible example:
> https://github.com/hadley/devtools/wiki/Reproducibility
>
> To post: email ggp...@googlegroups.com
> To unsubscribe: email ggplot2+u...@googlegroups.com
> More options: http://groups.google.com/group/ggplot2
>
> ---
> You received this message because you are subscribed to the Google Groups
> "ggplot2" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to ggplot2+u...@googlegroups.com.
> For more options, visit https://groups.google.com/groups/opt_out.

Brian Danielak

unread,
Feb 22, 2014, 10:10:06 PM2/22/14
to ggp...@googlegroups.com, Brian Danielak
Dennis,

Thanks for your reply; I appreciate the brute-force approach. What I was wondering was specifically about having properly-formatted fractions. For example, it's certainly formatting exponents using pretty-print with my current code, so I figured there must be a way to properly pretty-print fractions too.

- B

Ista Zahn

unread,
Feb 23, 2014, 2:04:19 PM2/23/14
to Brian Danielak, ggplot2
I'm not sure how "pretty" you want them to be, but there is a
fractions() function in the MASS package that converts from e.g., 0.5
==> 1/3, 0.14 ==> 7/50 etc. If you want "pretty" as in what plotmath
"frac" gives you I'm not sure... I guess you could parse the result
from fractions() to separate out the numerator and denominator and
construct the labels from these using bquote().

Best,
Ista

On Sat, Feb 22, 2014 at 10:10 PM, Brian Danielak
Reply all
Reply to author
Forward
0 new messages