本文分享一套可直接运行的 R 语言批量绘图脚本,适用于基因表达量分析,自动为每个基因生成带误差棒、原始散点、t 检验 P 值的专业柱形图,一键批量出图,无需手动调整。
散点+柱状图+差异检验(标注P值)+科学配色
脚本完整保留原始代码,无任何修改,直接复制即可使用
# 设置工作路径 setwd("F:/画图") getwd() # 加载包 library(ggplot2) library(dplyr) library(tidyr) # ===================== 1. 读取数据 ===================== df <- read.table( "gene.txt", header = FALSE,sep = "\t", stringsAsFactors = FALSE) # ===================== 批量循环画图 ===================== all_genes <- df[, 1] for (i in 1:nrow(df)) { gene_now <- all_genes[i] dat <- df[i, ] # 提取各组表达量 d3_ctrl <- as.numeric(dat[1, 2:4]) d3_cys <- as.numeric(dat[1, 5:7]) d7_ctrl <- as.numeric(dat[1, 8:10]) d7_cys <- as.numeric(dat[1, 11:13]) d12_ctrl <- as.numeric(dat[1, 14:16]) d12_cys <- as.numeric(dat[1, 17:19]) # 统计检验 p3 <- t.test(d3_ctrl, d3_cys)$p.value p7 <- t.test(d7_ctrl, d7_cys)$p.value p12 <- t.test(d12_ctrl, d12_cys)$p.value # 构建均值±SD数据 plot_data <- data.frame( Time = c("D3","D3","D7","D7","D12","D12"), Treat = rep(c("Control","+Cys"), 3), Mean = c(mean(d3_ctrl), mean(d3_cys), mean(d7_ctrl), mean(d7_cys), mean(d12_ctrl), mean(d12_cys)), SD = c(sd(d3_ctrl), sd(d3_cys), sd(d7_ctrl), sd(d7_cys), sd(d12_ctrl), sd(d12_cys)) ) # 构建原始散点数据 point_data <- data.frame( Time = rep(c("D3","D3","D7","D7","D12","D12"), each=3), Treat = rep(c("Control","+Cys"), each=3, 3), Value = c(d3_ctrl, d3_cys, d7_ctrl, d7_cys, d12_ctrl, d12_cys) ) # 固定顺序 plot_data$Time <- factor(plot_data$Time, levels = c("D3","D7","D12")) plot_data$Treat <- factor(plot_data$Treat, levels = c("Control","+Cys")) point_data$Time <- factor(point_data$Time, levels = c("D3","D7","D12")) point_data$Treat <- factor(point_data$Treat, levels = c("Control","+Cys")) # P值标签(斜体P) p_text <- data.frame( Time = c("D3","D7","D12"), y = max(plot_data$Mean + plot_data$SD) * 1.25, label = c( paste0("italic(P) == ", round(p3, 3)), paste0("italic(P) == ", round(p7, 3)), paste0("italic(P) == ", round(p12, 3)) ) ) # 绘图:柱子 + 误差棒 + 原始散点 + P值 p <- ggplot(plot_data, aes(x=Time, y=Mean, fill=Treat)) + geom_col(position=position_dodge(0.8), width=0.7, color="black") + geom_errorbar(aes(ymin=Mean-SD, ymax=Mean+SD), width=0.2, position=position_dodge(0.8), size=0.4) + # 原始真实值散点 geom_point(data=point_data, aes(x=Time, y=Value, group=Treat), position=position_jitterdodge(jitter.width=0.1, dodge.width=0.8), size=1.8, color="black", stroke=0.8) + geom_text(data=p_text, aes(x=Time, y=y, label=label), inherit.aes=FALSE, size=4.5, parse=TRUE) + scale_fill_manual(values=c("#457B9D","#E63946")) + labs(x="Days", y="Expression Level", title=gene_now) + theme_bw(base_size=14) + theme(plot.title=element_text(hjust=0.5), legend.position="top") # 输出PDF ggsave(paste0(gene_now,".pdf"), p, width=6, height=5, device="pdf") cat("已完成:", gene_now, "\n") } cat("========== 画图完成 ==========\n")出图结果: