我想在 R 和 ggplot2 中创建一个直方图,其中根据连续的 x 值填充箱。大多数教程仅通过离散值或密度/计数进行着色。
按照这个例子,我们可以用彩虹刻度为垃圾箱着色:
df <- data.frame(x = runif(100))
ggplot(df) +
geom_histogram(aes(x), fill = rainbow(30))
Run Code Online (Sandbox Code Playgroud)
我想使用颜色渐变,其中垃圾箱从蓝色(最低)到黄色(最高)。该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
Run Code Online (Sandbox Code Playgroud)
我尝试了几种方法来为刻度提供 30 的长度,但每次都会遇到相同的错误。所以我的问题是:
scale_color_gradient该参数的函数是正确的fill还是我必须使用另一个函数?