【问题标题】:Is there a way to have a pdf using ggplot in a for loop and save it in R? [closed]有没有办法在for循环中使用ggplot生成pdf并将其保存在R中? [关闭]
【发布时间】:2020-05-11 09:07:14
【问题描述】:

我有这个数据集:

    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"
), date_time = structure(c(1427846400, 1427846400, 1427846400, 
1427846400, 1427846400, 1427846700, 1427846700, 1427846700, 1427846700, 
1427846700), class = c("POSIXct", "POSIXt"), tzone = "UTC"), 
    Date = structure(c(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"), Speed = c(59, 
    34, 46, 61, 46, 58, 39, 51, 36, 52), Total.Volume = c(7.5, 
    6, 6, 11.6, 7.2, 10, 8, 8, 7.2, 7.2), Ocupancy = c(0.8, 0.4, 
    0.6, 1.1, 1, 0.8, 0.7, 1.1, 0.8, 0.8), S.D = c(28.9, 17.8, 
    19.9, 24.4, 27.8, 23.6, 15.7, 15.3, 13.5, 26.6), Precipitation = c(0, 
    0, 0, 0, 0, 0, 0, 0, 0, 0)), row.names = c(NA, 10L), class = "data.frame")

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

【问题讨论】:

    标签: r pdf ggplot2 visualization gplots


    【解决方案1】:

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

    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'))
                                             }
    

    【讨论】:

    • 它没有用。我希望绘图在 X 轴上有时间,在 Y 轴上有速度和降水。收集代码使数据看起来很混乱。
    • 我有两个循环,首先我将遍历每个 Agency.Station.ID 以创建一个 pdf。然后我将遍历每个日期以在每个 pdf 文件中创建新页面。每个页面都有一个(时间 VS 速度和降水)图。
    • @mustafa 通常 ggplot 可以很好地处理长格式的数据,这就是收集功能的原因。您需要的结果由我的代码给出,它为每个 Agency.Station.ID 创建一个 pdf,并在其中“放置一个图”。试着把你的路径,看看它是否有效。
    • 我重新发布了这个问题,因为我认为我在这里没有说清楚,请参阅我的其他帖子。 pdf 中的一页不起作用,因为我需要为每个数据提供一个页面。
    猜你喜欢
    • 2018-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-30
    • 1970-01-01
    • 2022-12-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多