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

Custom fill colour of bin with highest density in geom_histogram

我的示例数据框如下:

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 gradient and 这样的线程。 任何想法如何通常自定义填充直方图的箱子?

您需要将 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()