将 ggplot geom_histogram() 与 y-log-scale 和零箱一起使用

Using ggplot geom_histogram() with y-log-scale with zero bins

我有一个集合,其中有超过 10000 个整数,它们的值在 1 到 500 之间。 我想以直方图的形式绘制值,但是,由于只有少数整数的值大于 200,因此我想对 y 轴使用对数刻度。

问题出现了,当一个 bin 的计数为零时,因为对数值变为 -infinity。

为了避免这种情况,我想为每个 bin 添加一个 1 的伪计数。 在标准的 hist()-plot 中,我可以这样做:

hist.data = hist(data, plot=F, breaks=30)
hist.data$counts = log10(hist.data$counts + 1)
plot(hist.data, ...)

但是,我很难找到一种方法来访问 ggplot 中的计数。

有没有简单的方法可以做到这一点,或者有其他推荐的方法来处理这个问题?

实现此目的的一种方法是为 y 尺度编写您自己的转换函数。 ggplot2 使用的转换函数(例如使用 scale_y_log10() 时)在 scales 包中定义。

简答

library(ggplot2)
library(scales)

mylog10_trans <- function (base = 10) 
{
  trans <- function(x) log(x + 1, base)
  inv <- function(x) base^x
  trans_new(paste0("log-", format(base)), trans, inv, log_breaks(base = base), 
            domain = c(1e-100, Inf))
}

ggplot(df, aes(x=x)) + 
  geom_histogram() + 
  scale_y_continuous(trans = "mylog10")

输出

此图使用的数据:

df <- data.frame(x=sample(1:100, 10000, replace = TRUE))
df$x[sample(1:10000, 50)] <- sample(101:500, 50)

解释 trans 函数

让我们检查一下scales::log10_trans;它调用 scales::log_trans();现在,scales::log_trans打印为:

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

在上面的答案中,我替换了:

trans <- function(x) log(x, base)

与:

trans <- function(x) log(x + 1, base)