ggplot2 -log10 scale

This is how we can define custom axes transformations. You would need scales package.

require(ggplot2)
## Loading required package: ggplot2
require(scales)
## Loading required package: scales

Define the transformation (see also scales/R/trans-numeric.r):

#' -Log transformation.
#'
#' @param base base of logarithm
#' @aliases log_trans log10_trans log2_trans
#' @export log_trans log10_trans log2_trans
mlog_trans <- function(base = exp(1)) {
    trans <- function(x) -log(x, base)
    inv <- function(x) base^(-x)

    trans_new(paste("-log-", format(base), sep = ""), trans, inv, mlog_breaks(base = base))
}
mlog10_trans <- function() {
    mlog_trans(10)
}
mlog2_trans <- function() {
    mlog_trans(2)
}

Also define how the tick points are generated (note the call to this function from mlog_trans())

mlog_breaks <- function(n = 8, base = 10) {
    function(x) {
        rng <- -log(range(x, na.rm = TRUE), base = base)
        min <- floor(rng[2])
        max <- ceiling(rng[1])

        if (max == min) 
            return(base^(-min))

        by <- floor((max - min)/n) + 1
        rev(base^-seq(min, max, by = by))
    }
}

Use it in ggplot:

dat = data.frame(x = rnorm(100), y = rbeta(1000, 1, 10000))
ggplot(dat) + geom_point(aes(x = x, y = y)) + scale_y_continuous(trans = mlog10_trans())

plot of chunk unnamed-chunk-4