有没有办法在for循环中使用ggplot创建pdf并将其保存在R中?

我有这个数据集:

structure(list(Agency.Station.ID = c("MI270N003.6D", "MI270N004.7D", 
"MI270N005.7D", "MI270N007.3D", "MI270N008.5D", "MI270N003.6D", 
"MI270N004.7D", "MI270N005.7D", "MI270N007.3D", "MI270N008.5D", 
"MI270N003.6D", "MI270N004.7D", "MI270N005.7D", "MI270N007.3D", 
"MI270N008.5D", "MI270N003.6D", "MI270N004.7D", "MI270N005.7D", 
"MI270N007.3D", "MI270N008.5D"), date_time = structure(c(1427846400, 
1427846400, 1427846400, 1427846400, 1427846400, 1427846700, 1427846700, 
1427846700, 1427846700, 1427846700, 1427847000, 1427847000, 1427847000, 
1427847000, 1427847000, 1427847300, 1427847300, 1427847300, 1427847300, 
1427847300), class = c("POSIXct", "POSIXt"), tzone = "UTC"), 
    Date = structure(c(16526, 16526, 16526, 16526, 16526, 16526, 
    16526, 16526, 16526, 16526, 16526, 16526, 16526, 16526, 16526, 
    16526, 16526, 16526, 16526, 16526), class = "Date"), Time = c("00:00:00", 
    "00:00:00", "00:00:00", "00:00:00", "00:00:00", "00:05:00", 
    "00:05:00", "00:05:00", "00:05:00", "00:05:00", "00:10:00", 
    "00:10:00", "00:10:00", "00:10:00", "00:10:00", "00:15:00", 
    "00:15:00", "00:15:00", "00:15:00", "00:15:00"), Speed = c(59, 
    34, 46, 61, 46, 58, 39, 51, 36, 52, 62, 47, 49, 57, 50, 59, 
    50, 35, 54, 44), Total.Volume = c(7.5, 6, 6, 11.6, 7.2, 10, 
    8, 8, 7.2, 7.2, 9, 12, 8.7, 9.6, 7.6, 6, 5.6, 3.3, 8.4, 7.6
    ), Ocupancy = c(0.8, 0.4, 0.6, 1.1, 1, 0.8, 0.7, 1.1, 0.8, 
    0.8, 0.6, 1, 0.9, 1, 0.9, 0.6, 0.7, 0.3, 1, 0.9), S.D = c(28.9, 
    17.8, 19.9, 24.4, 27.8, 23.6, 15.7, 15.3, 13.5, 26.6, 31.6, 
    19.3, 27.8, 22.8, 26.4, 30.3, 26.1, 21.1, 26, 25.2), Precipitation = c(0, 
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)), row.names = c(NA, 
20L), class = "data.frame")

我希望每个Agency.Station.ID都有一个pdf文件。在每个pdf中都有一个日期页面,在每个页面中,我都希望有一个在x轴上具有时间并且在y轴上具有(速度和降水)的图。

评论
  • 请,带走
    请,带走 回复

    这里是一个快速而肮脏的解决方案:

    library(tidyverse)
    # first you've to work with your data, choosing the helpful columns
    dat1 <- dat[,c(1,3,5,9)]
    
    # then put them in long format
    dat1 <- dat1 %>% gather(variable, value,-c('Date','Agency.Station.ID'))
    
    # now the loop that creates the plots.pdf. Remember to add your path
    for (i in unique(dat1$Agency.Station.ID)){
                                              dat1 <- dat1[dat1$Agency.Station.ID==i,]
                                              ggplot(dat1,
                                                     aes(x = Date,
                                                         y = value,
                                                         group = variable,
                                                         color = variable)) + 
                                              geom_line() + geom_point()
                                              ggsave(paste0('C:\\addyourpath\\',i,'.pdf'))
                                             }