如何一次从分面图保存/生成多个单图?

How can I save / generated multiple single graphs from faceted graphs at once?

我有一个超过 100 个不同样本的数据集。样品来自不同的基因型(例如 X、Y、Z)和 4 个不同的时间点(T0、1、2、3),具有 3 个生物学重复(R1、2、3)。我正在测量 50 个不同基因的值(按行;A、B..)

longdata <- structure(list(Gene = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 
2L), .Label = c("A", "B"), class = "factor"), Genotype = structure(c(1L, 
1L, 1L, 1L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 1L, 1L, 1L, 1L, 2L, 
2L, 2L, 2L, 3L, 3L, 3L, 3L), .Label = c("X", "Y", "Z"), class = "factor"), 
    Time = structure(c(1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 
    3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L), .Label = c("T0", 
    "T1", "T2", "T3"), class = "factor"), Ave = c(1.32606106633333, 
    1.499956424, 1.118528738, 1.025082136, 0.424537206666667, 
    0.723243112666667, 0.335509156333333, 0.328275209, 0.788329993666667, 
    1.125292329, 2.357924224, 0.678921448, 0.222768019, 0.293117217, 
    0.548228048, 0.841192647333333, 3.144197864, 0.576764958333333, 
    1.32037215366667, 1.15039119233333, 1.03539976366667, 1.00032109266667, 
    0.740699933666667, 0.687992671666667), SE = c(0.119785209010494, 
    0.168580466330281, 0.264739468221289, 0.124588107424543, 
    0.194995686650518, 0.0392007703821249, 0.06203362889702, 
    0.0482287534807508, 0.396968455138007, 0.0903480171168777, 
    0.717823561374135, 0.164024037188693, 0.0078580995264886, 
    0.0980939303386436, 0.233081861930954, 0.0870744069976396, 
    0.324195222544884, 0.434640930315622, 0.0658409437053185, 
    0.135850334794207, 0.175517934316736, 0.123213160632528, 
    0.133598346586129, 0.203707785326976)), .Names = c("Gene", 
"Genotype", "Time", "Ave", "SE"), class = c("tbl_df", "tbl", 
"data.frame"), row.names = c(NA, -24L))

如何修改此语法以单独生成每个图形并将它们保存为 JPG/PNG 文件?

longdata %>% ggplot(aes(x = Time, y = Ave, fill = Genotype)) + geom_bar(position = position_dodge(), stat = "identity") + geom_errorbar(aes(ymin = Ave - SE, ymax = Ave + SE), width = 0.1, position = position_dodge(0.9)) + facet_wrap(~ Gene)

您可以将 ggplotggsave 放在一个循环中。

lapply(sort(unique(longdata$Gene)), function(i){
  ggplot(longdata[longdata$Gene == i, ], aes(x = Time, y = Ave, fill = Genotype)) + geom_bar(position = position_dodge(), stat = "identity") + geom_errorbar(aes(ymin = Ave - SE, ymax = Ave + SE), width = 0.1, position = position_dodge(0.9))
  ggsave(filename = paste0(i, ".png"))
})

此循环获取 Gene 的唯一元素,对它们进行排序,创建绘图,然后保存结果。