多ssGSEA数据集可视化及melt函数警告问题求助
问题解决方案
一、解决reshape2弃用&行名丢失问题
reshape2已经被tidyverse套件里的tidyr取代,用pivot_longer替代melt,同时先把行名转为显式列,就能完整保留样本ID:
处理单个数据框
library(tidyverse) # 给数据框添加样本列(原行名),再转换为长格式 t_ssgsea_OPC_long <- t_ssgsea_OPC %>% rownames_to_column(var = "sample") %>% pivot_longer( cols = -sample, # 排除样本列,把其他列转为长格式 names_to = "subtype", # 原列名存为subtype列 values_to = "ssgsea_score" # 评分值存为ssgsea_score列 )
批量处理4个数据框并合并
如果要把4个数据框整合到一起方便后续可视化,给每个数据框加个标识列再合并:
# 假设4个数据框分别是t_ssgsea_OPC、df2、df3、df4,放入列表并命名 all_datasets <- list( OPC = t_ssgsea_OPC, Dataset2 = df2, Dataset3 = df3, Dataset4 = df4 ) # 批量处理:添加样本列+数据集标识列,再合并为一个数据框 merged_long_data <- all_datasets %>% imap(~ .x %>% rownames_to_column("sample") %>% mutate(dataset = .y)) %>% # .y是列表中每个元素的名称(数据集名) bind_rows() %>% pivot_longer( cols = c(Classical, Mesenchymal, Neural, Proneural), names_to = "subtype", values_to = "ssgsea_score" )
二、4个相关图+16个柱状图的联合可视化
用ggplot2画图,patchwork拼接布局,完全满足需求:
1. 绘制4个数据集的亚型相关性热图
先定义一个批量画相关图的函数,再生成4个图:
# 定义单个相关性热图的绘制函数 plot_correlation <- function(df, plot_title) { # 计算亚型间的相关系数矩阵 corr_matrix <- cor(df[, c("Classical", "Mesenchymal", "Neural", "Proneural")]) # 转换为长格式用于ggplot绘图 corr_long <- corr_matrix %>% as.data.frame() %>% rownames_to_column("subtype1") %>% pivot_longer(cols = -subtype1, names_to = "subtype2", values_to = "corr_value") # 画热图 ggplot(corr_long, aes(subtype1, subtype2, fill = corr_value)) + geom_tile(color = "white") + geom_text(aes(label = round(corr_value, 2)), size = 3) + scale_fill_gradient2(low = "#2c7fb8", mid = "white", high = "#d95f02", midpoint = 0) + labs(title = plot_title, x = "", y = "") + theme_minimal() + theme(axis.text.x = element_text(angle = 45, hjust = 1)) } # 生成4个数据集的相关图 corr_plots <- all_datasets %>% imap(~ plot_correlation(.x, .y))
2. 绘制16个亚型评分的柱状图(每个数据集的每个亚型单独画)
基于之前合并的长格式数据,批量生成16个图:
# 按数据集+亚型分组,批量生成柱状图 bar_plots <- merged_long_data %>% group_by(dataset, subtype) %>% group_split() %>% map(~ ggplot(.x, aes(x = "", y = ssgsea_score)) + geom_bar(stat = "summary", fun = "mean", fill = "#7fcdbb", width = 0.6) + geom_errorbar(stat = "summary", fun.data = "mean_se", width = 0.2) + labs( title = paste(.x$dataset[1], .x$subtype[1]), y = "ssGSEA Score", x = "" ) + theme_minimal() + theme(plot.title = element_text(size = 10)) )
3. 拼接所有图形
用patchwork把4个相关图放在顶部一行,16个柱状图排成4行4列放在下方:
library(patchwork) # 组合相关图为一行 corr_row <- wrap_plots(corr_plots, nrow = 1) # 组合柱状图为4x4网格 bar_grid <- wrap_plots(bar_plots, nrow = 4, ncol = 4) # 拼接整体布局:相关图在上,柱状图在下 final_visualization <- corr_row / bar_grid # 添加总标题 final_visualization + plot_annotation( title = "ssGSEA Subtype Correlations and Score Distributions", theme = theme(plot.title = element_text(size = 14, hjust = 0.5)) )
内容的提问来源于stack exchange,提问作者driver
相关产品推荐
相关产品推荐

