如何在ggplot的函数中组合ggsave?

时间:2013-12-02 12:20:34

标签: r ggplot2

我用ggplot编写了这个小函数:

by(df, df$ID, function(i) {
  ggplot(i, aes(Date, EC))+
    geom_line() +
    geom_point() +
    ggtitle(unique(i$ID))
    })

这种方式ggplot绘制的图表数量与原始df中比较的ID数量相同。 现在,我必须将所有这些图保存为png图像,所以我的问题是:如何在我的函数中组合ggsave以便保存,例如ID1.png,ID2.png等?

这是我原来的df片段(它只有2个ID,但原来的ID超过20个):

structure(list(ID = structure(c(12L, 12L, 12L, 12L, 12L, 12L, 
12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 
12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 8L, 8L, 8L, 8L, 
8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 
8L, 8L, 8L, 8L), .Label = c("B0F", "B12T", "B1T", "B21T", "B22F", 
"B26T", "B2F", "B33F", "B3F", "B4F", "B7F", "P1", "P21", "P24", 
"P25", "P27", "P28", "P29"), class = "factor"), ph = c(6.8, 7.1, 
7, 7.01, 7.01, 6.97, 6.82, 6.9, 7.08, 6.87, 6.95, 6.78, 6.9, 
7.07, 6.71, 6.95, 6.74, 6.63, 6.78, 6.91, 6.84, 6.8, 6.76, 6.9, 
6.96, 6.94, 7, 6.94, 6.91, 6.76, 6.76, 6.82, 6.86, 6.68, 6.79, 
6.79, 6.81, 6.84, 6.64, 6.81, 6.82, 6.88, 6.76, 6.72, 6.68, 6.8, 
6.76, 6.76, 6.82, 7.3, 6.87, 6.87), EC = c(1840L, 940L, 820L, 
1035L, 767L, 951L, 971L, 443L, 950L, 799L, 980L, 990L, 964L, 
949L, 920L, 925L, 1000L, 856L, 898L, 625L, 838L, 2170L, 1499L, 
881L, 870L, 891L, 860L, 877L, 1094L, 1986L, 2030L, 886L, 2160L, 
1356L, 2090L, 2210L, 2070L, 2130L, 2050L, 2060L, 2080L, 2170L, 
2140L, 1303L, 2100L, 2170L, 1499L, 2120L, 2050L, 2160L, 2180L, 
2270L), Cl = c(132L, 102L, 111L, 108L, 99L, 90L, 109L, 100L, 
90L, 99L, 98L, 90L, 120L, 110L, 97L, 97L, 97L, 136L, 115L, 100L, 
100L, 280L, 460L, 110L, 91L, 88L, 81L, 88L, 349L, 333L, 362L, 
300L, 330L, 310L, 380L, 330L, 380L, 340L, 260L, 240L, 280L, 250L, 
320L, 280L, 290L, 280L, 460L, 240L, 210L, 260L, 280L, 260L), 
    Ca = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 
    NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 69L, 
    NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 
    NA, NA, NA, NA, NA, NA, NA, NA, 260L)), .Names = c("ID", 
"ph", "EC", "Cl", "Ca"), row.names = c(1L, 3L, 5L, 7L, 9L, 11L, 
13L, 15L, 17L, 19L, 21L, 23L, 25L, 27L, 29L, 31L, 33L, 35L, 37L, 
39L, 41L, 43L, 45L, 47L, 49L, 51L, 53L, 55L, 848L, 850L, 852L, 
854L, 856L, 858L, 860L, 862L, 864L, 866L, 868L, 870L, 872L, 874L, 
876L, 878L, 880L, 882L, 884L, 886L, 888L, 890L, 892L, 894L), class = "data.frame")

提前致谢

2 个答案:

答案 0 :(得分:2)

使用ggsave

invisible(by(df, df$ID, function(i) {
    p <- ggplot(i, aes(Date, EC))+
        geom_line() +
        geom_point() +
        ggtitle(unique(i$ID))
    ggsave(sprintf("file%s.pdf", unique(i$ID)),p)
}))

答案 1 :(得分:1)

假设您已将所有绘图都放在名为plist的变量中,则可以使用sapply

sapply(plist, function(x) ggsave(paste0(x$labels$title,".png"),x))