用自定义渐变填充直方图箱

Fill histogram bins with a custom gradient

我想在 R 和 ggplot2 中创建直方图,其中根据连续的 x 值填充 bin。大多数教程仅具有按离散值或 density/count.

着色的功能

以下 能够用彩虹色标尺为垃圾箱上色:

df <- data.frame(x = runif(100))

ggplot(df) +
  geom_histogram(aes(x), fill = rainbow(30))

Rainbow histogram

我想使用颜色渐变,其中 bins 从蓝色(最低)到黄色(最高)。 scale_fill_gradient() 函数似乎实现了这一点,但是当我将它插入到 rainbow() 的位置作为 fill 参数时,我收到一个错误:

> ggplot(df) +
+ geom_histogram(aes(x), fill = scale_fill_gradient(low='blue', high='yellow'))

Error: Aesthetics must be either length 1 or the same as the data (30): fill

我尝试了几种方法来为刻度提供 30 的长度,但每次都出现相同的错误。所以我的问题是:

  1. scale_color_gradientfill 参数的正确函数还是我必须使用另一个函数?
  2. 如果是正确的功能,我怎样才能正确提供长度?

如果你想为每个箱子使用不同的颜色,你需要在美学中指定fill = ..x..,这是geom_histogram的必要怪癖。将 scale_fill_gradient 与您喜欢的颜色渐变一起使用会产生以下输出:

ggplot(df, aes(x, fill = ..x..)) +
  geom_histogram() +
  scale_fill_gradient(low='blue', high='yellow')