Search code examples
rplot3dnormal-distributionrgl

3D Plot of normal distribution in R around a (x,y) point


I want to plot a univariate normal density function of the normal distribution onto a (x,y,z) coordinate system. The code I am using is:

library(rgl)
open3d()

x <- seq(0, 10, length=100)
y <- seq(0, 10, length=100)


z = outer(x,y, function(x,y) dnorm(x,2.5,1)*dnorm(y,2.5,1))

persp3d(x, y, z,col = rainbow(100))

enter image description here

The problem I an encountering is that I want the normal distribution not to be around its mean only but also to be on a straight line or a circle. In latter case, I would expect the output to be similar to a volcano. I guess I must first create some probabilities within a loop. How can I do this? Or should I also use some surface command to plot the output? I am pretty sure this has nothing to do with a bivariate normal though.

Best Fuji


Solution

  • The first part is easy: just don't let your z depend on y for instance:

    z = outer(x,y, function(x,y) dnorm(x,2.5,1))
    persp3d(x, y, z,col = rainbow(100))
    

    For the second part, you can imagine that the means of the normal distribution lie on the x^2+y^2=1 circle. You will have infinite normal distributions with radial directions. Try this:

    #define the volcano function
    volcano<-function(x,y,sigma=1/2) {
      alpha<-atan(y/x)+pi*(x<0)
      d<-sqrt((cos(alpha)-x)^2 + (sin(alpha)-y)^2)
      dnorm(d,0,sigma)
    }
    x<-seq(-2,2,length.out=100)
    y<-seq(-2,2,length.out=100)
    z<-outer(x,y,volcano)
    persp3d(x, y, z,col = rainbow(100))