[R] Several densityplots in single figure

David Winsemius dwinsemius at comcast.net
Wed Feb 22 14:48:36 CET 2012


On Feb 22, 2012, at 5:28 AM, josh rosen wrote:

> Hi,
>
> I have created two separate overlapping density plots- see example  
> code
> below.
> What I wish now to do is combine them into one figure where they sit  
> side
> by side.
> Any help would be great!
>
> many thanks in advance, josh.
>
> #####################
> thedataA <- data.frame(x1=rnorm(100,1,1),x2=rnorm(100,3,1)) #create  
> data
> thedataA.m<-melt(thedataA)
>
> densityplot(~value, thedataA.m,  
> groups=variable,auto.key=list(columns=2),
>       panel = function(x, y, ...) {
>               panel.densityplot(x, ...)
>               panel.abline(v=0)
>       }
> )
>

The syntax for grouping (which gives theoverlaid but different colors  
as default output) and "separation" is fairly simple. Use the "|"  
operator for separated plots and the " .., groups= <var>, .."   
parameter for overlaying results. It's only going to work easily if  
they are all in the same dataset.

Try:

   bigset <- cbind( rbind(thedataA.m, thedataB.m), ABgrp=rep(c("datA",  
"datB"), each=200) )
  densityplot(~value|ABgrp, data=bigset, groups=variable,  
auto.key=list(columns=2),
        panel = function(x, y, ...) {
                panel.densityplot(x, ...)
                panel.abline(v=0)   } )


And please work on whatever practice is producing duplicate postings.

-- 
David.



> thedataB <- data.frame(x1=rnorm(100,2,1),x2=rnorm(100,4,1)) #create  
> data
> thedataB.m<-melt(thedataA)

I assume that is a copy-paste-fail-to-correct error.

>
> densityplot(~value, thedataB.m,  
> groups=variable,auto.key=list(columns=2),
>       panel = function(x, y, ...) {
>               panel.densityplot(x, ...)
>               panel.abline(v=0)
>       }
> )
> ######################
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> 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.

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list