Search code examples
rcolorshistogram

Single histogram with two or more colors depending on xaxis values


I know it was already answered here, but only for ggplot2 histogram. Let's say I have the following code to generate a histogram with red bars and blue bars, same number of each (six red and six blue):

set.seed(69)
hist(rnorm(500), col = c(rep("red", 6), rep("blue", 7)), breaks = 10)

I have the following image as output: enter image description here

I would like to automate the entire process, how can I use values from any x-axis and set a condition to color the histogram bars (with two or more colors) using the hist() function, without have to specify the number os repetitions of each color?

Assistance most appreciated.


Solution

  • The hist function uses the pretty function to determine break points, so you can do this:

    set.seed(69)
    x <- rnorm(500)
    breaks <- pretty(x,10)
    col <- ifelse(1:length(breaks) <= length(breaks)/2, "red", "blue")
    hist(x, col = col, breaks = breaks)