tags:

views:

204

answers:

3

I want to create a histogram from a number of observations (i.e. d <- c(1,2.1,3.4,4.5) ) and then highlight the bin that a particular observation falls in, such that I have an output that looks like this: alt text

how do I do this in R?

+2  A: 
x = rnorm(100)
hist(x,br=10,col=c(rep(0,9),1))

Clearly this will color the last column so tweak the col= bit for your needs

Thanks

dangerstat

dangerstat
thats how i would do it. note, for typical colors like red and blue, you can enter in a string instead of the number: `col=c("red", "blue", 9)`
twolfe18
A: 

I was trying to do this with ggplot2, and was not able to come up with a perfect answer. you can do

dat<-data.frame(val=rnorm(100))
ggplot(data=dat,aes(x=val)) +
     geom_histogram(aes(fill=..count..==..count..[2]),binwidth=1)

but this breaks if multiple bins have the same count. any ideas?

Ian Fellows
+1  A: 

Expanding on dangerstat's answer, here is a little function that will automatically find which bin contains the value that you want to highlight:

highlight <- function(x, value, col.value, col=NA, ...){
   hst <- hist(x, ...)
   idx <- findInterval(value, hst$breaks)
   cols <- rep(col, length(hst$counts))
   cols[idx] <- col.value
   hist(x, col=cols, ...)
}

Now

x <- rnorm(100)
highlight(x, 1.2, "red")

will highlight the bin with 1.2 in it in red.

Aniko