3

So I have this data:

dataset     = rbinom(1000, 16, 0.5)
mean        = mean(dataset)
sd          = sd(dataset)
data_subset = subset(dataset, dataset >= (mean - 2*sd) & dataset <= (mean + 2*sd))

dataset     = data.frame(X=dataset)
data_subset = data.frame(X=data_subset)

And here's how I'm drawing my histogram for dataset:

ggplot(dataset, aes(x = X)) +
   geom_histogram(aes(y=..density..), binwidth=1, colour="black", fill="white") +
   theme_bw()

dataset

How can I shade the data_subset portion of the histogram, like so?

data_subset

hadley
  • 102,019
  • 32
  • 183
  • 245
surj
  • 4,706
  • 2
  • 25
  • 34

2 Answers2

5

My solution is very similar to joran's -- I think they're both worth looking at for the slight differences:

ggplot(dataset,aes(x=X)) +
   geom_histogram(binwidth=1,fill="white",color="black") +
   geom_histogram(data=subset(dataset,X>6&X<10),binwidth=1, 
   colour="black", fill="grey")+theme_bw() 

enter image description here

MattBagg
  • 10,268
  • 3
  • 40
  • 47
  • Accepting joran's answer because he was first.. I wish I could accept both, sorry! – surj Nov 12 '12 at 05:41
  • No problem (but you should use my code. :-) The aes inherit and you don't need a separate dataframe when you can subset within the ggplot) – MattBagg Nov 12 '12 at 05:47
2

Just add another geom_histogram line using that data subset (although you may have to tinker with the binwidth a bit, I'm not sure):

ggplot(dataset, aes(x = X)) +
   geom_histogram(aes(y=..density..), binwidth=1, colour="black", fill="white") + 
   geom_histogram(data = data_subset,aes(y=..density..), binwidth=1, colour="black",fill = "grey") +
   theme_bw()
joran
  • 169,992
  • 32
  • 429
  • 468