Search code examples
rggplot2histogramfillbins

Custom fill colour of bin with highest density in geom_histogram


My sample data frame goes as follows:

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))

I would like to create a histogram of binwidth = 1 and of the characteristics as follows:

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")

Now, what I cannot figure out is how to color just the bin of highest density (here, bin 8-9) with green color and all other bins with red (no gradient, just straight colors).

As you can see from the code above, the closest I could get to the desired outcome is to use scale_fill_continuous() component which is close but not exactly how I would like to see it. I tried threads like ggplot change fill colour without losing colour gradient and R - ggplot2 histogram conditional fill color. Any ideas how to generally custom fill histogram's bins?


Solution

  • You need to set the fill argument to a factor which takes 2 levels: one for all the density values lower then the max and one for the maximum density:

    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