Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plot 3d density

I want to create a 3d plot with densities.

I use the function density to first create a 2d dimensional plot for specific x values, the function then creates the density and puts them into a y variable. Now I have a second set of x values and put it again into the density function and I get a second set of y variables and so on.... I want to put those sets into a 3d plot, I hope you know what I mean. So I have a surface of densities....

E.g. I have:

x1<-c(1:10)
x2<-c(2:11)
y1<-c(1,1,2,1,3,4,2,3,2,2)
y2<-c(1,2,3,1,3,6,2,8,2,2)
.
.
.
.

Now I want to put on the x axis for the first value 1 the first set , on the y axis the corresponding x values and on the z axis the densities. So I have a "disk" for x=1, for x=2 I have the second "disk" and so on, so I get a density "mountain".

I hope I am understandable, if you have a better idea to realize it then you are welcome! I want to do it with the persp function, would be nice if you make an example with that function,

Thanks a lot for your help.

like image 747
user1690846 Avatar asked Nov 28 '12 15:11

user1690846


2 Answers

I'm afraid I can't make head or tail out of your question. But here is how you draw a plot of the sort I think you are looking for from a two dimensional dataset for which you first estimate the bivariate density:

x <- rnorm(1000)
y <- 2 + x*rnorm(1000,1,.1) + rnorm(1000)
library(MASS)
den3d <- kde2d(x, y)
persp(den3d, box=FALSE)

enter image description here

Then there are many options for persp, check out

?persp
like image 89
Peter Ellis Avatar answered Sep 21 '22 13:09

Peter Ellis


Building on Peter answer. The plot can now be more interesting, prettier and interactive with the plotly library.

x <- rnorm(1000)
y <- 2 + x*rnorm(1000,1,.1) + rnorm(1000)
library(MASS)
den3d <- kde2d(x, y)

# the new part:
library(plotly)
plot_ly(x=den3d$x, y=den3d$y, z=den3d$z) %>% add_surface()

which gives:

enter image description here

like image 26
Bastien Avatar answered Sep 20 '22 13:09

Bastien