R - Shading part of the 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 this is how I draw 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 data_subset part of the data_subset histogram, for example?

data_subset

+2
source share
3 answers

My solution is very similar to joran - I think they are both worth a look at 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

+4
source

Just add another geom_histogram line using this subset of the data (although you may have to work a bit with the binary, 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() 
+2
source

In fact, the original problem is not solved by two sentences. Joran used aes (y = .. density ..), while MattBagg ignored it. However, if you use the MattBagg solution, this is no longer density. If someone uses the solution proposed by Joran, the subset has its own density. Any ideas how to solve this? I tried to "mess with binwidth", but this does not solve the problem.

-1
source

Source: https://habr.com/ru/post/981986/


All Articles