首页 文章

在geom_histogram中具有最高密度的bin的自定义填充颜色

提问于
浏览
0

我的示例数据框如下:

a <- structure(list(Middlepoint = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 
12, 13, 14, 15, 16, 17, 18, 19, 1, 1, 5, 5, 4, 4, 3, 7, 18, 8, 
8, 8, 8, 8, 8.5, 8.5)), .Names = "Middlepoint", class = "data.frame", row.names = c(NA, 
-34L))

我想创建 binwidth = 1 的直方图,其特征如下:

library(ggplot2)
library(scales)
ggplot(a, aes(x = Middlepoint)) + 
  geom_histogram(aes(y = ..density.., fill=..density..), binwidth = 1) + 
  scale_x_continuous(breaks=0:19) + 
  scale_fill_continuous(low = "red", high = "green")

现在,我无法弄清楚的是如何用最高密度的箱子(这里,箱子8-9)用绿色和所有其他箱子用红色(没有渐变,只是直线颜色)着色 .

从上面的代码中可以看出,最接近我想达到的结果就是使用 scale_fill_continuous() 组件,这个组件很接近但不完全是我想要的 . 我尝试了像ggplot change fill colour without losing colour gradientR - ggplot2 histogram conditional fill color这样的线程 . 任何想法如何一般自定义填充直方图的箱子?

1 回答

  • 2

    您需要将 fill 参数设置为 factor ,它需要2个级别:一个用于所有密度值低于 max ,一个用于最大密度:

    ggplot(a, aes(x = Middlepoint)) + 
      geom_histogram(aes(y    = ..density.., 
                         fill = cut(..density.., c(0, sort(..density.., TRUE)[1:2]))), 
                     binwidth = 1) + 
      scale_fill_manual("", values = c("red", "green")) +
      theme_minimal()
    

    Histogram

相关问题