1
votes

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.

2
Is this really dependent on x-axis values or do you just want an even number of bars. Is that really the plot you got with seed 69? I get a different plot with 7 blue bars. There are not equal numbers of bars. - MrFlick
@MrFlick No, running this example code I got the same result every time! (6 blue- 6 red). And yes, it depends on x-axis values. - Fábio

2 Answers

2
votes

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

When I want to do this, I actually tabulate the data and make a barplot as follows (note that a bar plot of tabulated data is a histogram):

 set.seed(69)
 dat <- rnorm(500, 0, 1)
 tab <- table(round(dat, 1))#Round data from rnorm because rnorm can be precise beyond most real data
 bools <- (as.numeric(attr(tab, "name")) >= 0)#your condition here
 cols <- c("grey", "dodgerblue4")[bools+1]#Note that FALSE + 1 = 1 and TRUE + 1 = 2
 barplot(tab, border = "white", col = cols, main = "Histogram with barplot")

The output:

enter image description here