MIT & Harvard发表的顶刊审美,代码来了!
本次使用R语言复现一下Nature图,作者来自Broad Institute of MIT和 Harvard!
原图每个子图重复设置,看起来杂乱;复现时,所有子图共享x轴标题、共享y轴标题,更清爽。
✅读入测试数据!
✅关键代码,
# 创建基础ggplot图形,设置x轴为年龄(Age),y轴为基因表达量(Expression)p <- ggplot(glutamatergic, aes(x = Age, y = Expression)) +# 添加线性平滑曲线:使用线性模型,灰色半透明区域表示置信区间 geom_smooth(aes(group = 1), method = "lm", formula = y ~ x, se = TRUE, color = "black", alpha = 0.3, linewidth = 0.8, show.legend = FALSE) +# 添加散点:点的颜色按Status分组,设置透明度和大小 geom_point(aes(color = Status), alpha = 0.7, size = 2.5, stroke = 1, show.legend = FALSE) +# 设置分面:按Subtype分组,每行5个子图,y轴刻度自由调整[1,2,3] facet_wrap(~ Subtype, ncol = 5, scales = "free_y") + # 添加统计标签:显示每个Subtype的统计结果(如相关系数和p值) geom_text(data = facet_stats_all, aes(x = x_pos_adjusted, y = y_pos_adjusted + 0.2, label = label), hjust = -0.1, vjust = -0.5, size = 4, fontface = "plain", show.legend = FALSE, lineheight = 0.9, color = "black")✅这是一张分面图,包含海量信息:
每个子图中添加分组散点图(Control为绿色、SCZ为红色); 每个子图添加整体数据(All)的趋势线+置信区间(灰色阴影); 每个子图添加统计结果标签Spearman秩相关系数(ρ)、假设检验的p值(p),每组标签按分组设置颜色(All组标签为灰色,Control组标签为绿色、SCZ组标签为红色);
✅值得学习的R可视化知识点:
geom_smooth添加趋势线和置信区间,method设置趋势线拟合方法,se开启置信区间,
# 趋势线+置信区间添加 geom_smooth(aes(group = 1), method = "lm", formula = y ~ x, se = TRUE, color = "black", alpha = 0.3, linewidth = 0.8, show.legend = FALSE)Spearman秩相关系数(ρ)、假设检验的p值(p)的计算方法,
spearman_test <- cor.test(data$Age, data$Expression, method = "spearman")label = paste0("ρ=", round(spearman_test$estimate, 2), #spearman相关系数", ", format_p_value(spearman_test$p.value # p值 ))分面方法的使用,
facet_wrap(~ Subtype, ncol = 5, scales = "free_y") #按照Subtype分面,每行5列,y轴标题共享分面方法的使用,也可参考之前的内容👉:复现IF50.0期刊上6张图,换数据即可用!
科学计数法,小数位数设置方法,
# 将科学计数法转换为×10^格式 sci_format <- format(p, scientific = TRUE, digits = 2) parts <- strsplit(sci_format, "e")[[1]] base <- as.numeric(parts[1]) exponent <- as.numeric(parts[2])return(sprintf("p=%.1f×10^%d", base, exponent))patchwork的design参数精确控制布局,ab前4个图上下对齐,b中第5个图留白,
layout_design <- "AAAAABBBB#"# 应用自定义布局combined_plot <- figa + figb + plot_layout(design = layout_design, heights = c(1, 1))如果不设置,则会出现杂乱的排列,
本期结束!
获取绘图代码+测试数据+数据处理方法+依赖包安装方法,
👇(备注:299)
(加入学习,收费,备注:299)