【问题标题】:Fill histogram bins with a custom gradient使用自定义渐变填充直方图箱
【发布时间】:2018-05-03 08:22:26
【问题描述】:

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

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

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

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

Rainbow histogram

我想使用颜色渐变,其中 bin 从蓝色(最低)到黄色(最高)。 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】:

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

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

    【讨论】:

    • 谢谢你——正是我想要的。我之前也遇到过其他变量,例如 ..count....density..,但无法找到确切的数量或数量。
    猜你喜欢
    • 1970-01-01
    • 2017-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-08
    • 2022-11-15
    • 2010-12-07
    相关资源
    最近更新 更多