使用ggplot2绘制基因表达谱——处理后不同时间点RNA-seq数据可视化
使用ggplot2绘制Cluster2基因表达谱的完整步骤
没问题,我来帮你一步步用ggplot2画出cluster2的基因表达谱~首先咱们得先把数据和工具都准备好:
1. 加载必要的R包
咱们需要用ggplot2来绘图,dplyr来整理数据——直接加载tidyverse更省心,它包含了这两个包和其他常用工具:
library(tidyverse)
2. 整理你的数据
从你给出的cluster2表格来看,那个名为rownames的列其实是基因名称对吧?为了避免和数据框自带的行名混淆,咱们先把它重命名成gene:
# 重命名列,消除歧义 cluster2 <- cluster2 %>% rename(gene = rownames)
另外,你的Sample是时间序列(比如Sample1是第一个时间点,Sample2是第二个),一定要把它转换成有序因子,不然ggplot会默认按字母顺序排序,打乱时间顺序:
# 按你的时间点顺序定义因子水平,这里假设你有Sample1、Sample2...按需添加 cluster2$Sample <- factor(cluster2$Sample, levels = c("Sample1", "Sample2", "Sample3"), ordered = TRUE)
你可以用str(cluster2)检查一下数据结构,确保gene是字符型,Sample是有序因子,expression是数值型。
3. 绘制基因表达谱
根据你的需求,我提供几种常用的绘图方案:
方案1:多基因折线图(展示每个基因随时间的变化)
如果想同时看所有基因在不同时间点的表达趋势,用折线+散点的组合最直观:
ggplot(cluster2, aes(x = Sample, y = expression, group = gene, color = gene)) + geom_line(linewidth = 1) + # 折线展示趋势 geom_point(size = 2) + # 散点标记每个时间点的具体表达量 labs(title = "Cluster2基因表达趋势(不同时间点)", x = "时间点", y = "标准化表达量", color = "基因名称") + theme_minimal() + theme( axis.text.x = element_text(angle = 45, hjust = 1), # 旋转x轴标签避免重叠 plot.title = element_text(hjust = 0.5, size = 14) # 标题居中并调整大小 )
方案2:分面折线图(避免多基因拥挤)
如果基因数量多,上面的图会很拥挤,这时候用分面把每个基因单独展示:
ggplot(cluster2, aes(x = Sample, y = expression)) + geom_line(linewidth = 1, color = "#2c3e50") + geom_point(size = 2, color = "#e74c3c") + facet_wrap(~gene, ncol = 3) + # 按基因分面,每行3个图 labs(title = "Cluster2单个基因表达谱", x = "时间点", y = "标准化表达量") + theme_minimal() + theme( strip.text = element_text(size = 10), # 调整分面标签大小 plot.title = element_text(hjust = 0.5, size = 14) )
方案3:箱线图(展示每个时间点的基因表达分布)
如果你想看每个时间点下cluster2所有基因的表达分布情况,用箱线图+散点的组合:
ggplot(cluster2, aes(x = Sample, y = expression)) + geom_boxplot(fill = "#3498db", alpha = 0.7) + # 箱线展示分布 geom_jitter(width = 0.2, color = "#2c3e50", size = 1) + # 散点展示单个基因的表达 labs(title = "Cluster2基因表达分布(不同时间点)", x = "时间点", y = "标准化表达量") + theme_minimal() + theme(plot.title = element_text(hjust = 0.5, size = 14))
这些代码你可以根据自己的实际数据(比如更多时间点、更多基因)调整参数,比如修改颜色、分面数量、标签大小等等。
内容的提问来源于stack exchange,提问作者Nicolas
相关产品推荐
相关产品推荐

