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

问题描述 投票:1回答:1

我想在R和ggplot2中创建一个直方图,其中根据它们的连续x值填充区间。大多数教程仅通过离散值或密度/计数进行着色。

以下this example能够用彩虹尺度为垃圾箱着色:

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

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

Rainbow histogram

我想使用颜色渐变,其中容器从蓝色(最低)到黄色(最高)。 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. 如果它是正确的功能,我怎样才能正确提供长度?
r ggplot2 histogram gradient
1个回答
1
投票

如果你想为每个箱子设置不同的颜色,你需要在美学中指定fill = ..x..,这是geom_histogram的必要特征。使用scale_fill_gradient和您喜欢的颜色渐变,然后产生以下输出:

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

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.