1

I have generated these data:

dat = MASS::mvrnorm(n = 50, 
                mu = c(1, 5),
                Sigma = matrix(c(1, 0.5, 0.5, 1), nrow = 2),
                empirical = TRUE)

I can generate a 2D histogram with the following code:

plot_ly(x = dat[,1], y = dat[,2], type = "histogram2dcontour")

enter image description here

How can I generate a plot of these same data in 3D - either as a 3D histogram or 3D kernel density distribution?

grug
  • 33
  • 4

2 Answers2

3

Have you tried bivariate? First, assuming you have two columns - x and y

library(bivariate)
colnames(dat) <- c("x", "y")
dat <- as.data.frame(dat)
f = kbvpdf (dat$x, dat$y, 0.7, 7)
plot (f, TRUE, xlab="x", ylab="y")

enter image description here

Another option would be:

# install.packages("plot3D")
library(plot3D)
##  Calculate joint counts at cut levels:
z <- table(dat$x, dat$y)

##  Plot as a 3D histogram:
hist3D(z=z, border="black")

enter image description here

Or as 2d heatmap:

##  Plot as a 2D heatmap:
image2D(z=z, border="black")

enter image description here

MAPK
  • 5,635
  • 4
  • 37
  • 88
0

Using kde2d from MASS and plotly

dens2d <- kde2d(dat[,1],dat[,2])

fig <- plot_ly(x=dat[,1], y=dat[,2], z=dens2d$z) 

fig <- fig %>% add_surface()
Ahmed Attia
  • 153
  • 1
  • 8