R - Shading part of a ggplot2 histogram

寵の児 提交于 2019-12-21 20:31:42

问题


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

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


回答1:


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




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


来源:https://stackoverflow.com/questions/13337811/r-shading-part-of-a-ggplot2-histogram

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!