Question

I am trying to format my axes on a log scale from Rpy2 using ggplot. In ordinary R, it's possible to do:

qplot(data=data, x=x, y=y) + geom_point() + scale_y_log2()

To get a log2 axis. When I try to use ggplot2.scale_y_log2 in Rpy2, it complains that it's not found, although ggplot2.scale_x_log10 (log*10*) works fine. How can I get log2 axes in Rpy2?

Related question: if my data is already logged (e.g. it's in a Pandas dataframe where I applied log2 to the rows), how can I get ggplot in Rpy2 to just format the axis as a log axis (i.e. ticks like 2^1, 2^2, 2^4, ...) without taking the log again of the data? Just a reformatting of the labels, since the data is already in log values. thanks.

Was it helpful?

Solution

Since this is a Python / rpy2 question, the code in Python:

from rpy2.robjects.lib import ggplot2
from rpy2.robjects import r
from rpy2.robjects.packages import importr

scales = importr('scales')

iris = r('iris')

p = ggplot2.ggplot(iris) + \
    ggplot2.geom_point(ggplot2.aes_string(x="Sepal.Length", y="Sepal.Width")) + \
    ggplot2.scale_x_continuous(trans = scales.log2_trans())

p.plot()

OTHER TIPS

To answer your first part of the question , you can't do this in R:

qplot(data=data, x=x, y=y) + geom_point() + scale_y_log2()

you get this error :

   Error: could not find function "scale_y_log2"

So, you have to define it before:

library(scales)
scale_y_log2 <- function (...) 
{
  scale_y_continuous(..., trans = log2_trans())
}
dat <- data.frame(x=1:10,y=1:10)
qplot(data=dat, x=x, y=y) + geom_point() + scale_y_log2()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top