0

I have generated a data with 3 columns and these data points correspond to 3 different clusters that is shown at the 4th column.

I would like to plot these points on a 3d plot where each class A,B,C is shown with a specific color. here is the generation of data:

n1 <- 10
n2 <- 10
n3 <- 10
n <- n1 + n2 + n3

mu1 <- c(1,2,1)
mu2 <- c(2,2,0)
mu3 <- c(8,1,2)

d <- 3
x1 <- mu1 + rnorm(d*n1, mean = 0, sd = 0.5)
dim(x1) <- c(d,n1)
x2 <- mu2 + rnorm(d*n2, mean = 0, sd = 0.5)
dim(x2) <- c(d,n2)
x3 <- mu3 + rnorm(d*n3, mean = 0, sd = 0.5)
dim(x3) <- c(d,n3)

x <- cbind(x1,x2,x3)
y <- rep(c("A","B","C"), c(n1,n2,n3))
xx <- as.data.frame(t(x))
xx$sample <- y

Here is what I am trying for plotting. But I would like each point represent the color of its class.

library(plotly)
plot_ly(x=xx$V1, y=xx$V2, z=xx$V3, type="scatter3d", mode="markers")

I would like to use ggplot as follow to get 3d plot. the following code is giving me the 2d graph of the points.

p1 <- ggplot(xx, aes(V1, V2,V3, colour = sample )) +
  geom_point(size = 3)+
  scale_x_continuous(limits = c(-2, 10))+
  scale_y_continuous(limits = c(-2, 4))+
  guides(colour = guide_legend(override.aes = list(shape = 15, size = 3)))+
  theme_bw()
p1

Do you have any idea how can I generate the 3d plot? Thanks

say.ff
  • 373
  • 1
  • 7
  • 21
  • 1
    ggplot2 on its own generates static charts, and is not made for 3d. There are a variety of related packages to add 3d effects, like `gg3D` and `ggforce` like here: https://www.data-imaginist.com/2017/i-made-a-3d-movie/ For the moment, you could add color to your plotly solution with `plot_ly(x=xx$V1, y=xx$V2, z=xx$V3, type="scatter3d", color = xx$sample, mode="markers")`. Is that sufficient? – Jon Spring Dec 08 '19 at 20:03
  • 1
    You can also mimic 3d effects by projecting your coordinates into fake 3d space, and use alpha etc to imitate distance: https://twitter.com/JustTheSpring/status/1048711474468728832 – Jon Spring Dec 08 '19 at 20:07

1 Answers1

0

As mentioned by @Jon Spring, you can use gg3D package. You can follow this answer from a previous post: How to plot 3D scatter diagram using ggplot?

devtools::install_github("AckerDWM/gg3D") # to install it
library("gg3D")
qplot(x=0, y=0, z=0, geom="blank") + 
  theme_void() +
  axes_3D()

And then, you can add you ggplot like that:

ggplot(xx, aes(x = V1, y = V2, z = V3, color = sample))+
  theme_void()+
  axes_3D()+
  stat_3D()

enter image description here

Alternatively, you can use plot3d function from rgl package to get a 3D visualization of your plot:

colors = c("red","blue","green")
plot3d(xx[,1:3], col = colors[as.factor(xx$sample)], pch = 16)
legend3d("topright",legend = unique(xx$sample),col = colors, pch = 16, cex = 2)

Here is a snapshot of the window: enter image description here

dc37
  • 15,840
  • 4
  • 15
  • 32