如何用颜色渐变填充直方图?

How to fill histogram with color gradient?

我有一个简单的问题。如何使用固定 binwidth 并填充彩虹色(或任何其他调色板)的 ggplot2 绘制直方图?

假设我有这样的数据:

myData <- abs(rnorm(1000))

我想绘制直方图,使用例如binwidth=.1。然而,这将导致不同数量的垃圾箱,具体取决于数据:

ggplot() + geom_histogram(aes(x = myData), binwidth=.1) 

如果我知道垃圾箱的数量(例如 n=15),我会使用类似的东西:

ggplot() + geom_histogram(aes(x = myData), binwidth=.1, fill=rainbow(n))

但是随着 bin 数量的变化,我有点陷入了这个简单的问题。

如果你真的想要灵活的垃圾箱数量,这是我的小解决方法:

library(ggplot2)

gg_b <- ggplot_build(
  ggplot() + geom_histogram(aes(x = myData), binwidth=.1)
)

nu_bins <- dim(gg_b$data[[1]])[1]

ggplot() + geom_histogram(aes(x = myData), binwidth=.1, fill = rainbow(nu_bins))

如果 binwidth 是固定的,这里有一个替代解决方案,它使用内部函数 ggplot2:::bin_breaks_width() 在创建图形之前 获取 bin 的数量。它仍然是一种解决方法,但避免像 :

那样调用 geom_histogram() 两次
# create sample data
set.seed(1L)
myData <- abs(rnorm(1000))
binwidth <- 0.1

# create plot    
library(ggplot2)   # CRAN version 2.2.1 used
n_bins <- length(ggplot2:::bin_breaks_width(range(myData), width = binwidth)$breaks) - 1L
ggplot() + geom_histogram(aes(x = myData), binwidth = binwidth, fill = rainbow(n_bins)) 


作为第三种选择,聚合可以在 ggplot2 之外完成。然后,可以使用 geom_col() 代替 geom_histogram():

# start binning on multiple of binwidth
start_bin <- binwidth * floor(min(myData) / binwidth)
# compute breaks and bin the data
breaks <- seq(start_bin, max(myData) + binwidth, by = binwidth)
myData2 <- cut(sort(myData), breaks = breaks, by = binwidth)

ggplot() + geom_col(aes(x = head(breaks, -1L), 
                        y = as.integer(table(myData2)), 
                        fill = levels(myData2))) + 
  ylab("count") + xlab("myData")

请注意,breaks 绘制在 x 轴上而不是 levels(myData2) 以保持 x 轴连续。否则,将绘制每个因子标签,这会使 x 轴混乱。另请注意,使用内置 ggplot2 调色板而不是 rainbow().