用自定义渐变填充直方图箱 [英] Fill histogram bins with a custom gradient
问题描述
我想在R和ggplot2中创建一个直方图,其中垃圾箱基于它们的连续x值填充.大多数教程仅以离散值或密度/计数来着色.
I want to create a histogram in R and ggplot2, in which the bins are filled based on their continuous x-value. Most tutorials only feature coloring by discrete values or density/count.
按照此示例,可以使用彩虹鳞片:
Following this example was able to color the bins with a rainbow scale:
df <- data.frame(x = runif(100))
ggplot(df) +
geom_histogram(aes(x), fill = rainbow(30))
我想使用一种颜色渐变,其中垃圾箱从蓝色(最低)到黄色(最高). scale_fill_gradient()
函数似乎可以达到目的,但是当我将它插入rainbow()
代替fill
参数时,我收到一个错误:
I want to use a color gradient, where the bins are from blue (lowest) to yellow (highest). The scale_fill_gradient()
function seems to achive that, yet when i insert it in place of rainbow()
for the fill
argument i receive an error:
> 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的长度,但是每次都会遇到相同的错误.所以我的问题是:
I tried several ways to supply the length of 30 for the scale, yet i get the same error every time. So my question is:
-
scale_color_gradient
是fill
参数的正确函数还是我必须使用另一个函数? - 如果功能正确,如何正确提供长度?
- Is
scale_color_gradient
the right function for thefill
argument or do i have to use another one? - If it is the right function, how can i correctly supply the length?
推荐答案
如果要为每个容器使用不同的颜色,则需要在美观中指定fill = ..x..
,这是geom_histogram
的必要要求.将scale_fill_gradient
与您喜欢的颜色渐变一起使用会产生以下输出:
If you want different colors for each bin, you need to specify fill = ..x..
in the aesthetics, which is a necessary quirk of geom_histogram
. Using scale_fill_gradient
with your preferred color gradient then yields the following output:
ggplot(df, aes(x, fill = ..x..)) +
geom_histogram() +
scale_fill_gradient(low='blue', high='yellow')
这篇关于用自定义渐变填充直方图箱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!