复现Nature子刊图,换数据即可用!
本次使用R语言复现Nature Communications上的3张图
✅读入测试数据!
✅关键代码,
# 主绘图函数
plot_figure <- function(fig_id, legend_title) {
df <- data_merged %>% filter(Figure == fig_id)
# 计算每组最大值用于放置p值
max_y_df <- df %>%
group_by(Gene, Group) %>%
summarise(max_y = max(Value, na.rm = TRUE) + 5, .groups = "drop")
# 合并最大值
df <- left_join(df, max_y_df, by = c("Gene", "Group"))
ggplot(df, aes(x = Gene, y = Value, fill = Group)) +
# 添加bar
geom_bar(
stat = "summary", fun = mean,
position = position_dodge(width = 0.7), width = 0.7, color = "black", # 添加黑色边框
) +
# 添加bar上方的errorbar
geom_errorbar(
stat = "summary", fun.data = mean_se,
position = position_dodge(0.8), width = 0.2
) +
# 添加bar上方的抖动散点图
geom_jitter(
position = position_jitterdodge(dodge.width = 0.8), stroke = 0.5,
size = 2.0, alpha = 0.8, color = "black", shape = 21,
show.legend = FALSE# 图例中只展示bar、不展示jitter散点
) +
# 添加bar的样本数,n=。。。。。。
geom_text(aes(label = paste0("n=", n), y = 5),
position = position_dodge(0.7),
angle = 90, size = 3, hjust = 0, vjust = 0.5, color = "black"
) +
# 添加bar上方的p值
geom_text(
aes(label = ifelse(Group == "shRNA-1", pval_1, pval_2), y = max_y * 1.1),
position = position_dodge(0.7),
size = 2.4, vjust = -0.2, hjust = 0.5, color = "black",
angle = 90
) +
# 添加水平虚线辅助线
geom_hline(yintercept = 100, linetype = "dashed", color = "gray40")
✅值得学习的R可视化知识点:
🔸errorbar添加,
# 添加bar上方的errorbar
geom_errorbar(
stat = "summary", fun.data = mean_se,
position = position_dodge(0.8), width = 0.2
)
效果见圆圈中,
🔸文本text添加,
# 添加bar的样本数,n=。。。。。。
geom_text(aes(label = paste0("n=", n), y = 5),
position = position_dodge(0.7),
angle = 90, size = 3, hjust = 0, vjust = 0.5, color = "black"
) +
# 添加bar上方的p值
geom_text(
aes(label = ifelse(Group == "shRNA-1", pval_1, pval_2), y = max_y * 1.1),
position = position_dodge(0.7),
size = 2.4, vjust = -0.2, hjust = 0.5, color = "black",
angle = 90
)
🔸多子图拼接,
plot_grid(
plot_2b, plot_2c, plot_2d,
labels = c("b", "c", "d"), # 每个子图左上角的标签文字
label_size = 14, # 标签字体大小
label_fontface = "bold", # 标签字体加粗
label_x = 0, # 标签在子图中的水平位置(0=最左, 1=最右)
label_y = 1, # 标签在子图中的垂直位置(0=最下, 1=最上)
hjust = -0.2, # 标签相对 label_x 的水平偏移(负值向左)
vjust = 1.2, # 标签相对 label_y 的垂直偏移(>1 往上)
ncol = 1, # 布局为1列
align = "v"# 垂直方向对齐
)总之,该图是抖动散点图+ barplot的组合,可以学习p值添加、多子图拼接、文本text使用等,值得学习。
正文结束!
数据+详细代码👇
(备注:299)