Force bars to start from a lower value than 0 in ggplot geom_bar in R

后端 未结 1 1605
猫巷女王i
猫巷女王i 2021-01-16 09:36

I want to plot bar plots using ggplot. I used scale_y_log10 to rescale the y axis. When use the script below, I get bars that are in both directions (upward and downward) an

相关标签:
1条回答
  • 2021-01-16 10:00

    You can define your own scale, instead of using scale_y_continuous(trans="log10")). In the example below, you will have to change the argument from=-2 to you specific example.

    # defining example data (since I don't have your data)
    data(mtcars)
    mtcars <- rbind(mtcars, mtcars)
    mtcars <- rbind(mtcars, mtcars)
    mtcars <- rbind(mtcars, mtcars)
    mtcars <- rbind(mtcars, mtcars)
    mtcars[1, "cyl"] <- 2
    # sample plot
    c <- ggplot(mtcars, aes(factor(cyl))) + geom_bar()
    c + scale_y_log10() # this starts from 1
    # defining the scale change
    require(scales)
    mylog_trans <- function(base=exp(1), from=0) 
    {
      trans <- function(x) log(x, base)-from
      inv <- function(x) base^(x+from)
      trans_new("mylog", trans, inv, log_breaks(base=base), 
                domain = c(base^from, Inf))
    }
    # 
    c + scale_y_continuous(trans = mylog_trans(base=10, from=-2)) # starts from 1e-2 
    c + scale_y_continuous(trans = mylog_trans(base=10, from=-5)) # starts from 1e-5
    

    As you can see in the above example, this plot can be very misleading. The two plots display the same data, but look very different, so be careful when using this scale-change.

    0 讨论(0)
提交回复
热议问题