如何创建函数来为每一列生成图

How do I create function to generate plot for each column

这是一个示例数据集:

Group<-c("Blue","Red","Green","Blue","Red","Green")
UV<-c("3","4","2","5","4","6")
Rain<-c("10","11","12","15","16","17")

dmean<-data.frame(Day,Group,UV,Rain)

Day<-c("1","1","1","1","1","1","2","2","2","2","2","2",)
Group<-c("Blue","Blue","Red","Red","Green","Green","Blue","Blue","Red","Red","Green","Green")
UV<-c("3","3.1","4","4.1","2","2.2","5","5.1","4","4.2","6.1","6.1")
Rain<-c("10","10.1","11","11","12","12.2","15","15.2","16","16.1","17","17.2")

dpoints<-data.frame(Day,Group,UV,Rain)

基本上,我有一个包含多个变量的大型数据集,在此示例中,“UV”和“Rain”按“Day”和“Group”分组。我想为每一列生成一个图,例如使用几何线连接“dmean”的平均值的“UV”和“Rain”,以及使用下面可能不正确的函数的“dpoints”中的数据点不完整:

plot.ts <- function(d){
  
  ggplot(dmean, aes(x = Day, y = col.num+2, group = Group, colour = Group)) +
    geom_line(size = 1)+
    geom_point(dpoints, aes(y = d0[,col.num+2]),
               alpha = .2) +
    facet_wrap(~Group, 
               ncol = 1) +
    ggsave(paste0("plot1_",col.num,".png"), width = 15, height = 10, dpi = 300, units = "in", device='png')
  
}

这是我希望与其他变量一起生成的“UV”示例图。 有人可以检查函数并通过列应用函数吗?

要实现您<我们想要的结果,您必须对函数进行一些调整。首先,我创建了一个函数 plot.ts,它接受一个参数,即要映射到 y 上的列的名称。其次,在 ggplot() 中,我使用了 rlang 包中的 .data 代词,它允许在 ggplot 中使用列名作为字符串。之后,您可以使用 lapply 遍历所需列的列表来创建您的绘图:

library(ggplot2)

plot.ts <- function(yvar) {
  ggplot(dmean, aes(x = Day, y = .data[[yvar]], group = Group, colour = Group)) +
    geom_line(size = 1)+
    geom_point(data = dpoints, aes(y = .data[[yvar]]), alpha = .2) +
    facet_wrap(~Group, ncol = 1) +
    labs(title = yvar)
    #ggsave(paste0("plot1_",col.num,".png"), width = 15, height = 10, dpi = 300, units = "in", device='png')
}

lapply(c("UV", "Rain"), plot.ts)
#> [[1]]

#> 
#> [[2]]