1

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.

Community
  • 1
  • 1
Fábio
  • 771
  • 2
  • 14
  • 25
  • 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 Mar 17 '17 at 19:36
  • @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 Mar 20 '17 at 14:14

2 Answers2

2

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)
thc
  • 9,527
  • 1
  • 24
  • 39
  • That's nice! I didn't know this 'pretty()' function. I'm going to use your suggestion in my code and I return with feedback! – Fábio Mar 20 '17 at 15:00
2

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

Phantom Photon
  • 768
  • 2
  • 10
  • 20
  • Your solution is very interesting, but I really need the 'hist()' function, so I can play easily with breaks values. – Fábio Mar 20 '17 at 14:37