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

时间:2017-10-06 11:15:09

标签: r ggplot2 data.table mapply

感兴趣的数据位于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

非常感谢任何帮助

1 个答案:

答案 0 :(得分:1)

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

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个地块。

第一个:

enter image description here

如果你想存储:

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]

分别访问这些图表