【问题标题】:plotting points with 3 dimension in 3s plots using ggplots package使用 ggplots 包在 3s 图中绘制 3 维的点
【发布时间】:2019-12-08 19:17:08
【问题描述】:

我生成了一个包含 3 列的数据,这些数据点对应于 3 个不同的集群,显示在第 4 列。

我想将这些点绘制在 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 绘图吗? 谢谢

【问题讨论】:

  • ggplot2 自己生成静态图表,不适合 3d。有多种相关的软件包可以添加 3d 效果,例如 gg3Dggforce 如下所示:data-imaginist.com/2017/i-made-a-3d-movie 目前,您可以使用 plot_ly(x=xx$V1, y=xx$V2, z=xx$V3, type="scatter3d", color = xx$sample, mode="markers") 为您的绘图解决方案添加颜色。够了吗?
  • 您还可以通过将坐标投影到假 3d 空间中来模拟 3d 效果,并使用 alpha 等来模拟距离:twitter.com/JustTheSpring/status/1048711474468728832

标签: r ggplot2 3d scatter-plot ggplotly


【解决方案1】:

正如@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()

或者,您可以使用 rgl 包中的 plot3d 函数来获得绘图的 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)

这是窗口的快照:

【讨论】:

    猜你喜欢
    • 2020-11-14
    • 1970-01-01
    • 2011-01-05
    • 1970-01-01
    • 1970-01-01
    • 2019-04-10
    • 2017-09-14
    • 1970-01-01
    • 2019-03-09
    相关资源
    最近更新 更多