2

I am going to plot the 3D surface of a bivariate normal distribution and its contours (it could be any bivariate normal distribution). I want to use persp and contour in my drawing. I searched on the Internet, but I found many ways to do it. Most of them have used some packages. But I would like to do this in a way that uses fewer packages or even without installing any package (however, I do not know it is possible). Could you please show me your own way with an example of a bivariate normal distribution? [Fewer packages, better solution]. Indeed I would like to see the simplest way of drawing a surface and contours of a bivariate normal distribution.

Rojer
  • 335
  • 2
  • 9

1 Answers1

5

You can do just about anything you like in R without using packages, as long as you are prepared to write your own code to do it. Visualising a 2d surface is possible in just a few lines of R code using persp and contour, but generating the surface (i.e. creating a 2d density plot, is not trivial.

Here is how you can generate a 2d bivariate normal distribution surface using just the mnormt package (as requested in the comments). For this example, I have made up a dummy variance-covariance matrix.

library(mnormt)

x     <- seq(-5, 5, 0.25) 
y     <- seq(-5, 5, 0.25)
mu    <- c(0, 0)
sigma <- matrix(c(2, -1, -1, 2), nrow = 2)
f     <- function(x, y) dmnorm(cbind(x, y), mu, sigma)
z     <- outer(x, y, f)

contour(x, y, z)


persp(x, y, z, theta = -30, phi = 25, 
      shade = 0.75, col = "gold", expand = 0.5, r = 2, 
      ltheta = 25, ticktype = "detailed")

Created on 2020-06-17 by the reprex package (v0.3.0)

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
  • Thank you so much @AllanCameron. Can we use mnormt package for making a bivariate normal distribution? If yes, how can you use the suitable functions of this package in your first code? – Rojer Jun 17 '20 at 15:24
  • @vahid it would have been useful if you had mentioned that in your initial question. You said the less packages the better. Of course you can generate a bivariate normal distribution with mnormt. Are you asking how to do that? – Allan Cameron Jun 17 '20 at 15:36
  • Yes @AllanCameron. I would like to see how you change your first above solution and use mnormt package in it (the first solution that you have used mass package). – Rojer Jun 17 '20 at 15:58
  • Thank you so much @AllanCameron. I have accepted your solution. – Rojer Jun 17 '20 at 16:54
  • Thanks again @AllanCameron. I did it. – Rojer Jun 18 '20 at 19:02
  • Hello @AllanCameron. I hope you see my new message. In your above code which is: mu<-c(0, 0); sigma <-matrix(c(2, -1, -1, 2), nrow = 2); f<- function(x, y); dmnorm(cbind(x, y), mu, sigma); z<- outer(x, y, f), what is the algebraic expression z=f(x,y)? – Rojer Jun 23 '20 at 18:25
  • @vahid `outer(x, y, f)` just calls `dmnorm` on each pair of x and y co-ordinates for the given mu and sigma. The value `z` is the density at `x, y` – Allan Cameron Jun 23 '20 at 19:14