[R] how to plot two histograms overlapped in the same plane coordinate

Frank E Harrell Jr f.harrell at Vanderbilt.Edu
Fri Jul 9 18:45:58 CEST 2010


Empirical CDFs are much better for this purpose, and allow 
superpositioning (see e.g. the Ecdf function in the Hmisc package). 
Otherwise look at histbackback in Hmisc.

Frank

On 07/09/2010 11:40 AM, Andrew Miles wrote:
>
>
> I'm not sure what you are trying to do. Do you want one histogram for
> males and one for females on the same graph? If so, the simplest way to
> put two histograms together is to simply use the add parameter:
>
> age.males=age[which(sex=="M")]
> age.females=age[which(sex=="F")]
>
> hist(age.males, col="blue")
> hist(age.females, add=T)
>
> The only problem is that the hist() function does not do
> semi-transparency. I am not sure if other packages do. The code above
> will give you a blue histogram for males, and clear histogram for
> females on top of it. You'll probably have to manually alter the axes of
> the histogram to give the histograms for males and females the same
> break points (i.e. where one bar stops and another begins). See ?hist
> for more information about that.
>
> Andrew Miles
> Department of Sociology
> Duke University
>
> On Jul 9, 2010, at 9:29 AM, Mao Jianfeng wrote:
>
>> Dear R-help listers,
>>
>> I am new. I just want to get helps on how to plot two histograms
>> overlapped in the same plane coordinate. What I did is very ugly.
>> Could you please help me to improve it? I want to got a plot with semi-
>> transparent overlapping region. And, I want to know how to specify the
>> filled colors of the different histograms.
>>
>> I also prefer other solutions other than ggplot2.
>>
>> Many thanks to you.
>>
>>
>> What I have done:
>>
>> library(ggplot2)
>>
>> age<-c(rnorm(100, 1.5, 1), rnorm(100, 5, 1))
>> sex<-c(rep("F",100), rep("M", 100))
>> mydata<-cbind(age, sex)
>> mydata<-as.data.frame(mydata)
>> head(mydata)
>>
>>
>> qplot(age, data=mydata, geom="histogram", fill=sex, xlab="age",
>> ylab="count", alpha=I(0.5))
>>
>>
>> Best,
>>
>>
>> Mao J-F
>>
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide
>> http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>


-- 
Frank E Harrell Jr   Professor and Chairman        School of Medicine
                      Department of Biostatistics   Vanderbilt University



More information about the R-help mailing list