How to suppress zeroes when using geom_histogram with scale_y_log10

后端 未结 1 1444
猫巷女王i
猫巷女王i 2021-01-11 18:31

I\'m trying to plot a histogram with a log y scale using ggplot, geom_histogram and scale_y_log10. Most regions (those with counts greater than 1) appear correct: the backgr

相关标签:
1条回答
  • 2021-01-11 19:04

    You can add drop=TRUE to the geom_histogram call to drop bins with zero counts (see ?stat_bin for details):

    set.seed(1)
    df <- data.frame(E=sample(runif(100), 20, TRUE))
    ggplot(df,aes(E)) + 
      geom_histogram(binwidth=0.1, drop=TRUE) + 
      scale_y_log10(limits=c(0.1,100)) + 
      xlim(0,1)
    

    EDIT: Since the scale starts at 1, it is impossible to display a bar of height 1. As mentioned in this answer, you can choose to start at different levels, but it may become misleading. Here's the code for this anyway:

    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))
    }
    
    ggplot(df,aes(E)) + 
      geom_histogram(binwidth=0.1, drop=TRUE) + 
      scale_y_continuous(trans = mylog_trans(base=10, from=-1), limits=c(0.1,100)) +
      xlim(0,1)
    
    0 讨论(0)
提交回复
热议问题