Question

I have a graph in ggplot2 (via rpy2) that formats the x axis on a log2 scale:

p += ggplot2.scale_x_continuous(trans=scales.log2_trans(),
                                   breaks=scales.trans_breaks("log2",
                                                              robj.r('function(x) 2^x'),
                                                              n=8),
                                   labels=scales.trans_format("log2", robj.r('math_format(2^.x)')))

If the x values are already in log2, how can I just apply the formatting transformation of scales, to make the values appear in 2^x format, rather than a decimal log2 value? I.e. if I were to drop the trans= argument, how can I still format the ticks correctly?

Was it helpful?

Solution 2

Guessing that math_format() is in scales (can't check it right now), and based on Brian's answer the rpy2 version should be the following:

from rpy2.robjects.lib import ggplot2
from rpy2.robjects.packages import importr
scales = importr("scales")
p = ggplot2.ggplot(mtcars) + \
        ggplot2.aes_string(x="wt", y="mpg")) + \ 
        ggplot2.geom_point() + \
        ggplot2.scale_x_continuous(labels = scales.math_format("2^.x"))
p.plot()

OTHER TIPS

I can give the answer in pure R, but I don't know rpy2 to be able to translate it.

Effectively, you just specify the labels argument which controls how the labels are displayed; don't change the trans or breaks argument which affect the overall scaling and where the breaks appear. Using mtcars as an example:

library("ggplot2")
library("scales")
ggplot(mtcars, aes(wt, mpg)) + 
  geom_point() +
  scale_x_continuous(labels = math_format(2^.x))

enter image description here

(Obviously that doesn't make sense since the weight is not already on a log base 2 scale, but the concept works.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top