How to get a reversed, log10 scale in ggplot2?

前端 未结 2 773
执念已碎
执念已碎 2020-11-27 17:19

I\'d like to make a plot with a reversed, log10 x scale using ggplot2:

require(ggplot2)
df <- data.frame(x=1:10, y=runif(10))
p <- ggplot(data=df, aes(         


        
2条回答
  •  南方客
    南方客 (楼主)
    2020-11-27 17:49

    The link that @joran gave in his comment gives the right idea (build your own transform), but is outdated with regard to the new scales package that ggplot2 uses now. Looking at log_trans and reverse_trans in the scales package for guidance and inspiration, a reverselog_trans function can be made:

    library("scales")
    reverselog_trans <- function(base = exp(1)) {
        trans <- function(x) -log(x, base)
        inv <- function(x) base^(-x)
        trans_new(paste0("reverselog-", format(base)), trans, inv, 
                  log_breaks(base = base), 
                  domain = c(1e-100, Inf))
    }
    

    This can be used simply as:

    p + scale_x_continuous(trans=reverselog_trans(10))
    

    which gives the plot:

    enter image description here

    Using a slightly different data set to show that the axis is definitely reversed:

    DF <- data.frame(x=1:10,  y=1:10)
    ggplot(DF, aes(x=x,y=y)) + 
      geom_point() +
      scale_x_continuous(trans=reverselog_trans(10))
    

    enter image description here

提交回复
热议问题