R - 着色ggplot2直方图的一部分

时间:2012-11-12 02:56:37

标签: r ggplot2 histogram

所以我有这些数据:

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)

以下是我为dataset绘制直方图的方法:

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

dataset

如何遮蔽直方图的data_subset部分,如此?

data_subset

2 个答案:

答案 0 :(得分:5)

我的解决方案与joran非常相似 - 我认为他们都值得关注这些细微的差异:

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

答案 1 :(得分:2)

只需使用该数据子集添加另一条geom_histogram行(尽管您可能需要修改一下binwidth,但我不确定):

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