其他
PCA、RDA等排序图的一些三维可视化示例
scatterplot3d包绘制三维散点图。
按“pca_site.txt”的group1区分颜色,按group2区分点的形状。
#数据pca_site <- read.delim('pca_site.txt', sep = '\t', stringsAsFactors = FALSE)
pca_var <- read.delim('pca_var.txt', sep = '\t', stringsAsFactors = FALSE)
#scatterplot3d 包,详情 ?scatterplot3d
library(scatterplot3d)
scatterplot3d(pca_site$PC1, pca_site$PC2, pca_site$PC3, color = rep(c('red2', 'purple2', 'green3'), c(8, 8, 8)), pch = rep(rep(c(17, 15), c(4, 4)), 3),
xlab = paste('PCA1: 20%'), ylab = paste('PCA2: 12%'), zlab = paste('PCA3: 8%'))
scatterplot3d(pca_site[2:4], color = rep(c('red2', 'purple2', 'green3'), c(8, 8, 8)), lwd = 3, type = 'h',
xlab = paste('PCA1: 20%'), ylab = paste('PCA2: 12%'), zlab = paste('PCA3: 8%'))
rgl包绘制三维散点图,交互式风格便于观测数据。
按“pca_site.txt”的group1区分颜色。
#rgl 包,交互式,详情 ?plot3dlibrary(rgl)
plot3d(pca_site[2:4], col = rep(c('red2', 'purple2', 'green3'), c(8, 8, 8)), size = 5)
#参考自:https://stackoverflow.com/questions/24282143/pca-multiplot-in-r
#有其它需要(如颜色选择等),自定义修改即可
library(rgl)
plotPCA <- function(x, nGroup) {
n <- ncol(x)
if(!(n %in% c(2,3))) { # check if 2d or 3d
stop("x must have either 2 or 3 columns")
}
fit <- hclust(dist(x), method="complete") # cluster
groups <- cutree(fit, k=nGroup)
if(n == 3) { # 3d plot
plot3d(x, col=groups, type="s", size=1, axes=F)
axes3d(edges=c("x--", "y--", "z"), lwd=3, axes.len=2, labels=FALSE)
grid3d("x")
grid3d("y")
grid3d("z")
} else { # 2d plot
maxes <- apply(abs(x), 2, max)
rangeX <- c(-maxes[1], maxes[1])
rangeY <- c(-maxes[2], maxes[2])
plot(x, col=groups, pch=19, xlab=colnames(x)[1], ylab=colnames(x)[2], xlim=rangeX, ylim=rangeY)
lines(c(0,0), rangeX*2)
lines(rangeY*2, c(0,0))
}
}
plotPCA(pca_site[2:4], nGroup = 3)
car包结合rgl包绘制三维散点图,交互式风格便于观测数据。
按“pca_site.txt”的group1区分颜色,同时按group1添加分组椭圆(注意这个椭圆不是置信区间,仅为标记分组的曲面)。
#car+rgl 包,交互式,详情 ?scatter3dlibrary(car)
library(rgl)
scatter3d(pca_site$PC1, pca_site$PC2, pca_site$PC3, surface = FALSE, point.col = rep(c('red2', 'purple2', 'green3'), c(8, 8, 8)),
xlab = paste('PCA1: 20%'), ylab = paste('PCA2: 12%'), zlab = paste('PCA3: 8%'))
scatter3d(pca_site$PC1, pca_site$PC2, pca_site$PC3, groups = as.factor(pca_site$group1), surface = FALSE, ellipsoid = TRUE,
xlab = paste('PCA1: 20%'), ylab = paste('PCA2: 12%'), zlab = paste('PCA3: 8%'))
还有广泛熟知的plotly包绘制三维散点图,交互式网页的风格便于观测数据。
按“pca_site.txt”的group1区分颜色,以及添加变量向量等。
#plotly 包,网页交互式,详情 ?plot_lylibrary(plotly)
pca_site$color <- rep(c('red2', 'purple2', 'green3'), c(8, 8, 8))
plot_ly(pca_site, labels = ~name, x = ~PC1, y = ~PC2, z = ~PC3, color = ~color)
#添加变量向量
#参考自:https://stackoverflow.com/questions/44393823/3d-biplot-in-plotly-r
library(plotly)
p <- plot_ly() %>%
add_trace(x = pca_site$PC1, y = pca_site$PC2, z = pca_site$PC3,
type="scatter3d", mode="markers",
marker = list(color=rep(c(1,2,3), each = 8), opacity = 0.7))
for (k in 1:nrow(pca_var)) {
p <- p %>% add_trace(x=c(0, pca_var[k,'PC1']), y=c(0, pca_var[k,'PC2']), z=c(0, pca_var[k,'PC3']),
type="scatter3d", mode="lines",
line = list(width=3),
opacity = 1)
}
p