[R] plotting a marginal distribution on the plane behind a persp() plot

Colin Rowat c.rowat at bham.ac.uk
Fri Oct 18 14:50:31 CEST 2013


Dear Duncan,

Thank you for your quick reply.   I've got the basic version of what I'm looking for now (see below).  My next step will be your rgl::persp3d suggestion for the hidden lines control.

Best,

Colin 

library(MASS)

X <- mvrnorm(1000,mu=c(0,0),Sigma=matrix(c(1,0,0,1),2))

X.kde <- kde2d(X[,1],X[,2],n=25) # X.kde is list: $x 1*n, $y 1*n, $z n*n

persp(X.kde,phi=30,theta=60,xlab="x_b",ylab="x_a",zlab="f") ->res

c<-17
lines(trans3d(rep(X.kde$x[c],25), X.kde$y, X.kde$z[c,],pmat=res),col="red",lwd=2)

marg <- rowSums(X.kde$z)
mass <- sum(marg)
lines(trans3d(x=X.kde$x, y=rep(X.kde$y[25],25), z=marg/mass, pmat=res),col="green",lwd=2)

detach(package:MASS)

> -----Original Message-----
> From: Duncan Murdoch [mailto:murdoch.duncan at gmail.com]
> Sent: 15 October 2013 18:00
> To: Colin Rowat
> Cc: r-help at R-project.org
> Subject: Re: [R] plotting a marginal distribution on the plane behind a persp()
> plot
> 
> On 15/10/2013 11:38 AM, Colin Rowat wrote:
> > R'istas:
> >
> > I am trying to plot a marginal distribution on the plane behind a persp()
> plot.  My existing code is:
> >
> > library(MASS)
> >
> > X <- mvrnorm(1000,mu=c(0,0),Sigma=matrix(c(1,0,0,1),2))
> >
> > X.kde <- kde2d(X[,1],X[,2],n=25) # X.kde is list: $x 1*n, $y 1*n, $z
> > n*n
> >
> > persp(X.kde,phi=30,theta=60,xlab="x_b",ylab="x_a",zlab="f") ->res
> >
> > Any suggestions are very appreciated.
> 
> I would suggest not using persp() (use rgl::persp3d instead), but you can do it
> in persp using the same technique as in the 2nd example in the
> ?persp help page.   The difficulty with doing this is that persp() uses
> the painter's algorithm for hiding things, so if you want something hidden,
> you need to draw it first.  That's not always easy....
> 
> rgl::persp3d maintains a depth buffer so the order in which you draw things
> usually doesn't matter.  (The exception is with semi-transparent
> objects.)
> 
> Duncan Murdoch
> 



More information about the R-help mailing list