使用 mapply 以列名作为参数生成图

Use mapply to generate plots using column names as argument

感兴趣的数据在mymeanDT

DT <- data.table(yearmonth = as.yearmon(sample(seq(as.Date('2012/07/01'), as.Date('2016/02/28'),by="day"), 5000, replace = TRUE)),
             mydummy = as.factor(rbinom(5000, 1, .4)), X = runif(5000, 0, 1), Y = rnorm(5000, 20, 5), Z = runif(5000, 4, 6))

mymeanDT <- DT[, lapply(.SD, function(x) mean(x, na.rm = TRUE)), by = .(mydummy, yearmonth), .SDcols = c("X", "Y", "Z")]

我需要按 yearmonthmydummy 绘制所有列的线条。我可以用以下方法做到这一点

mycolnames <- c("X", "Y", "Z")
my_lapply_plots <- lapply(mymeanDT[, mycolnames, with = FALSE],function(mycol)
    ggplot(mymeanDT, aes(x = yearmonth,y = mycol)) +  
    geom_line(aes(linetype = mydummy, color = mydummy)) + scale_x_yearmon() + xlab("") + ylab("") +
    theme(plot.title = element_text(size = 14, hjust = -0.03)) +
    scale_linetype_manual(values=c("longdash", "solid"), breaks=c(0,1),labels=c("N", "Y")) +
    scale_color_manual(values=c("#701B45", "#007FAE"), breaks=c(0,1),labels=c("N", "Y")) +
    ggtitle(paste("Some", "title", sep = " "))
)

我想在标题中使用列名。所以我尝试通过 mapply

传递类似的函数
my_mapply_plots <- mapply(function(mycol, mynames) 
    ggplot(mymeanDT, aes(x = yearmonth,y = mycol)) +
    geom_line(aes(linetype = mydummy, color = mydummy)) + scale_x_yearmon() 
    + xlab("") + ylab("") +
    theme(plot.title = element_text(size = 14, hjust = -0.03)) +
    scale_linetype_manual(values=c("longdash", "solid"), breaks=c(0, 1), 
         labels=c("N", "Y")) +
    scale_color_manual(values=c("#701B45", "#007FAE"), breaks=c(0, 1), 
         labels=c("N", "Y")) +
    ggtitle(paste("Some", mycolnames, sep = " ")),
  mycol = mymeanDT[, mycolnames, with = FALSE], mynames = mycolnames)

但这是我得到的输出

my_mapply_plots
            X      Y      Z     
data        List,5 List,5 List,5
layers      List,1 List,1 List,1
scales      ?      ?      ?     
mapping     List,2 List,2 List,2
theme       List,1 List,1 List,1
coordinates ?      ?      ?     
facet       ?      ?      ?     
plot_env    ?      ?      ?     
labels      List,6 List,6 List,6

如有任何帮助,我们将不胜感激

我认为您应该使用 lapply 遍历 mycolnames-向量以获得所需的图。使用:

lapply(mycolnames, function(column) {
  ggplot(data = mymeanDT,
         aes(x = yearmonth, y = mymeanDT[[ column ]], linetype = mydummy, color = mydummy)) +
    geom_line()  + scale_x_yearmon() +
    ggtitle(paste("Some", column, sep = " "))
})

会给你3个地块。

第一个:

如果你想存储:

myplots <- lapply(mycolnames, function(column) {
  ggplot(data = mymeanDT,
         aes(x = yearmonth, y = mymeanDT[[ column ]], linetype = mydummy, color = mydummy)) +
    geom_line()  + scale_x_yearmon() +
    ggtitle(paste("Some", column, sep = " "))
})

键入 myplots 将打印这三个图。然后,您还可以使用 myplots[[1]](或:myplots[1]

单独访问这些图