R for statisticsR plot

三维点图和三维PCA图

2021-06-23  本文已影响0人  小洁忘了怎么分身

3dscatter

1.ggplot2画三维点图

很轻松找到了R包,然鹅不是很完美的样子。

#devtools::install_github("AckerDWM/gg3D")

library("gg3D")
library(ggplot2)

data(iris)
ggplot(iris, aes(x=Petal.Width, y=Sepal.Width, z=Petal.Length, color=Species)) + 
  theme_void() +
  axes_3D() +
  stat_3D()

2.scatterplot3d

一个不属于ggplot2体系的特立独行的R包,画起来还算简单。

参数pch表示形状,不同形状可以以数字1-24来代表。颜色的指定不支持映射,只能是把每个点的颜色设置好,传递给color参数。图例需要单独画,不能自动生成,但最终出土的颜值我还是喜欢的。sthda上面也有关于这个包的漂亮代码: http://www.sthda.com/english/wiki/scatterplot3d-3d-graphics-r-software-and-data-visualization

#install.packages("scatterplot3d")
library(scatterplot3d)
my_color = c("#66C2A5FF", "#FC8D62FF", "#8DA0CBFF")

colors = my_color[as.numeric(iris$Species)]

p1 = scatterplot3d(iris[,1:3],color = colors,main="iris",pch = 16)

legend(p1$xyz.convert(8.5, 2.5, 5), legend = levels(iris$Species),
      col = my_color, pch = 16)
p2 = scatterplot3d(iris[,1:3],color = "black",main="iris",pch = 21,bg = colors)
legend(p2$xyz.convert(8.5, 2.5, 5),col = "black", legend = levels(iris$Species),pt.bg =  my_color, pch = 21)

3.三维PCA图

PCA已经有好几个可视化的R包啦,把前三个主成分提取出来画三维点图也挺好看~

library(FactoMineR)
dat = iris[,1:4]
dat.pca = PCA(dat,graph = F)
a = dat.pca[["ind"]][["coord"]] 
p3 = scatterplot3d(a[,1:3],color = "black",main="iris",pch = 21,bg = colors)
legend("bottom",col = "black", legend = levels(iris$Species),pt.bg =  my_color, pch = 21,
       inset = -0.2, xpd = TRUE, horiz = TRUE)
my_pch = 22:24
pchs = my_pch[as.numeric(iris$Species)]

p4 = scatterplot3d(a[,1:3],color = "black",main="iris",pch = pchs,bg = colors)
legend("bottom",col = "black", legend = levels(iris$Species),pt.bg =  my_color, pch = my_pch,
       inset = -0.2, xpd = TRUE, horiz = TRUE)
上一篇 下一篇

猜你喜欢

热点阅读