我已经生成了一个包含3列的数据,这些数据点对应于第4列所示的3个不同的簇。
我想在3d图上绘制这些点,其中每个A,B,C类均以特定颜色显示。这是数据的生成:
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
这是我要绘制的内容。但是我希望每个点都代表其类的颜色。
library(plotly)
plot_ly(x=xx$V1, y=xx$V2, z=xx$V3, type="scatter3d", mode="markers")
我想使用ggplot来获取3d图。以下代码为我提供了点的二维图。
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
您知道如何生成3d图吗?谢谢
如@Jon Spring所述,您可以使用gg3D
包。您可以从以前的帖子中获得以下答案: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()
然后,您可以像这样添加ggplot
:
ggplot(xx, aes(x = V1, y = V2, z = V3, color = sample))+
theme_void()+
axes_3D()+
stat_3D()
或者,您可以使用plot3d
包中的rgl
函数来获取绘图的3D可视化:
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)