R:ggplot 在聚类分析后可视化每个聚类中的所有变量

R: ggplot to visualize all variables in each cluster after cluster analysis

如果 post 不清楚,请提前致歉。 所以我有我的数据框、74 个观察值和 43 列。我对它们进行了聚类分析。 然后我得到 5 个簇,并将簇号分配给每一行。 现在, 我的 df 有 74 行(obs)和 44 个变量。对于所有变量,我想在每个集群中绘制和查看哪些变量得到了丰富,哪些变量没有得到丰富。

我想通过ggplot来实现。 我想象中的输出面板是每行 5 个箱线图和 42 行图,每行将描述数据集中测量的一个变量。

数据集示例(抱歉,它很大,所以我做了一个例子,实际值不同)

df
ID    EGF   FGF_2    Eotaxin   TGF   G_CSF   Flt3L   GMSF   Frac IFNa2 .... Cluster
4300  4.21  139.32    3.10     0      1.81   3.48    1.86   9.51  9.41 ....    1
2345  7.19  233.10    0        1.81   3.48   1.86    9.41   0     11.4 ....    1
4300  4.21  139.32    4.59     0      1.81   3.48    1.86   9.51  9.41 ....    1
....
3457  0.19  233.10    0        1.99   3.48   1.86    9.41   0     20.4 ....    3
5420  4.21  139.32    3.10     0.56   1.81   3.48    1.86   9.51  29.8 ....    1
2334  7.19  233.10    2.68     2.22   3.48   1.86    9.41   0     28.8 ....    5

str(df)

$ ID        : Factor w/ 45 levels "4300"..... : 44 8 24 ....
$ EGF       : num ....
$ FGF_2     : num ....
$ Eotaxin   : num ....
....
$ Cluster   : Factor w/ 5 levels "1" , "2"...: 1 1 1.....3 1 5

#now plotting
#thought I pivot the datafram
new_df <- pivot_longer(df[,2:44],df$cluster, names_to = "Cytokine measured", values_to = "count")

#ggplot
ggplot(new_df,aes(x = new_df$cluster, y = new_df$count))+
geom_boxplot(width=0.2,alpha=0.1)+
geom_jitter(width=0.15)+
facet_grid(new_df$`Cytokine measured`~new_df$cluster, scales = 'free')

所以代码确实生成了一小块图表,符合我的想象输出。但我只能看到 5 行而不是 42 行。

所以回到 new_df,最后 3 列引起了我的注意:

Cluster    Cytokine measured    count
 1          EGF                 2.66
 1          FGF_2               390.1
 1          Eotaxin             6.75
 1          TGF                 0 
 1          G_CSF               520 
 3          EGF                 45
 5          FGF_2               4
 4          Eotaxin             0
 1          TGF                 0 
 1          G_CSF               43
 ....

所以簇数和计数列似乎是正确的,而测量的细胞因子只是不断重复 5 个变量名称,而不是我想要看到的总共 42 个变量。

我认为 table 转换步骤是错误的,但我不太清楚哪里出了问题以及如何解决。

请赐教

我们可以试试这个,我模拟了一些看起来像你的数据框的东西:

df =  data.frame(
ID=1:74,matrix(rnorm(74*43),ncol=43)
)
colnames(df)[-1] = paste0("Measurement",1:43)
df$cluster = cutree(hclust(dist(scale(df[,-1]))),5)
df$cluster = factor(df$cluster)

然后融化:

library(ggplot2)
library(tidyr)
library(dplyr)
melted_df = df %>% pivot_longer(-c(cluster,ID),values_to = "count")

g = ggplot(melted_df,aes(x=cluster,y=count,col=cluster)) + geom_boxplot() + facet_wrap(~name,ncol=5,scale="free_y")

您可以将其保存为更大的图来查看:

ggsave(g,file="plot.pdf",width=15,height=15)