# Get subplot of density histogram

Hi, maybe this is a fussy question, but I am interested in the following:
I have 2 data frames. The first one is just to have simple example. The second one is the well known diamonds data frame.

``````library(ggplot2)
my.data1<-data.frame(x=c(1,2,3,4,20))
my.data2<-diamonds
``````

I want to build a density-histogram:

``````ggplot(my.data1)+
geom_histogram(aes(x,y=after_stat(density)),breaks=c(0,10,20))
ggplot(my.data2)+
geom_histogram(aes(x=carat,y=after_stat(density)),breaks=seq(0,6,length.out=400))
``````

But now I am interested in a subplot:

``````ggplot(my.data1)+
geom_histogram(aes(x=x,y=after_stat(density)),breaks=c(0,10,20))+
xlim(0,10)
ggplot(my.data2)+
geom_histogram(aes(x=carat,y=after_stat(density)),breaks=seq(0,6,length.out=400))+
xlim(0,1)
``````

But these are no real subplots of the above ones. These are new histograms which use a subset of the data.

For the simple data frame we get the width=10 and height=0.1 (so 10*0.1=1). But I am interested in width=10 and height=0.8 (because the remaining part is in the range (10,20)).

With diamonds data we can see a similar behaviour.

Do you know how to solve this issue?
Thanks for help!
Arno

I think the following does the trick:

``````ggplot(my.data1)+
geom_histogram(aes(x=x,y=after_stat(density)),breaks=c(0,10,20))+
coord_cartesian(xlim=c(0,3))
``````
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.