Search code examples
rhistogram

R Histogram multiple color zones


I tried looking around to see how I can color code a generic histogram based on its range and I couldnt seem to find one on stack overflow. Im essentially trying to color code the two extreme ends of a histogram different colors. Is there a way to do so?

enter image description here

Thank you!


Solution

  • What about using cut?

    library(dplyr)
    library(ggplot2)
    
    dat <- data.frame(x = rnorm(1000, 11, 5))
    
    dat |> 
      mutate(z = cut(x, breaks = c(-Inf, 5, 15, +Inf))) |> 
      ggplot(aes(x, fill = z)) +
      geom_histogram()