surj
surj

Reputation: 4904

R - Shading part of a ggplot2 histogram

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

Upvotes: 3

Views: 4849

Answers (2)

MattBagg
MattBagg

Reputation: 10478

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

Upvotes: 5

joran
joran

Reputation: 173527

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()

Upvotes: 2

Related Questions