导入必要的包
library(factoextra)
library(Rtsne)
library("FactoMineR")#画主成分分析图需要加载这两个包
层次聚类要分成两个步骤:
- 计算距离
- 层次聚类
#先求样本之间两两相似性
result <- dist(df, method = "euclidean")
#产生层次结构
result_hc <- hclust(d = result, method = "ward.D2")
# 自行判断应该聚成几类
num_cluster = 4
out.id = cutree(result_hc, k=num_cluster)
out.id
#进行初步展示
fviz_dend(result_hc, k = num_cluster,
cex = 0.5,
k_colors = c("#2E9FDF", "#00AFBB", "#E7B800", "#FC4E07"),
color_labels_by_k = TRUE,
rect = TRUE
)
library(factoextra)
res <- hcut(sampleDists, k = 2, stand = TRUE)
# Visualize
fviz_dend(res,
# 加边框
rect = TRUE,
# 边框颜色
rect_border="cluster",
# 边框线条类型
rect_lty=2,
# 边框线条粗细
lwd=1.2,
# 边框填充
rect_fill = T,
# 字体大小
cex = 1,
# 字体颜色
color_labels_by_k=T,
# 平行放置
horiz=T)
然后tsne
# 设置一下随机种子
set.seed(42)
# 这里的perplexity是随机因素
tsne_out <- Rtsne(df,pca=FALSE,dims=2,
perplexity=30,theta=0.0)
head(tsne_out)
library(ggplot2)
tsne_res <- as.data.frame(tsne_out$Y)
colnames(tsne_res) <- c("tSNE1","tSNE2")
ggplot(tsne_res,aes(tSNE1,tSNE2,color=as.factor(out.id))) +
geom_point() + theme_bw() +
geom_hline(yintercept = 0,lty=2,col="red") +
geom_vline(xintercept = 0,lty=2,col="blue",lwd=1) +
theme(plot.title = element_text(hjust = 0.5)) +
labs(title = "tSNE plot",color="Species")+yuansh_theme
然后pca
table(group_list)
# 每次都要检测数据
dat[1:4,1:4]
## 下面是画PCA的必须操作,需要看说明书。
dat=t(dat)#画PCA图时要求是行名时样本名,列名时探针名,因此此时需要转换
dat=as.data.frame(dat)#将matrix转换为data.frame
dat=cbind(dat,group_list) #cbind横向追加,即将分组信息追加到最后一列
library("FactoMineR")#画主成分分析图需要加载这两个包
library("factoextra")
# The variable group_list (index = 54676) is removed
# before PCA analysis
dat.pca <- PCA(dat[,-ncol(dat)], graph = FALSE)#现在dat最后一列是group_list,需要重新赋值给一个dat.pca,这个矩阵是不含有分组信息的
fviz_pca_ind(dat.pca,
geom.ind = "point", # show points only (nbut not "text")
col.ind = dat$group_list, # color by groups
# palette = c("#00AFBB", "#E7B800"),
addEllipses = F, # Concentration ellipses
legend.title = "Groups"
)