【问题标题】:Create multiple lattice plots from a data table using lapply使用 lapply 从数据表创建多个格点图
【发布时间】:2015-05-27 08:11:33
【问题描述】:

我试图为众多变量(物种)中的每一个按组生成平均值,然后分别绘制每个变量。我尝试过列表和数据表格式。基本绘图功能在 for 循环中工作:

library(data.table)

      for (i in 3:5) {
      # generate a list of mean value for the species in column number i
      temp <- v2[, lapply(.SD, mean), by="Season", .SDcols=i]
      # plot each col of the list as a scatterplot with main title = header of 2nd col
      plot(temp[[2]]~temp[[1]], main = colnames(temp)[[2]])
    }

但是当我尝试创建格子图时,只会为最后一个变量生成一个图:

library(data.table)
library(lattice)

for (i in 3:5) {
  # generate a list of mean value by season for the species in column number i
  temp <- v2[, lapply(.SD, mean), by=c("Season", "Location"), .SDcols=i]
  # Each group in a separate mini plot
  xyplot(temp[[3]]~temp[[1]] | temp[[2]], main = colnames(temp)[3])
}

已尝试保存或打印每个格子图,这是正确的想法吗?也许我完全走错了路?

这是我的数据的一个小样本:

    structure(list(Location = structure(c(1L, 1L, 1L, 1L, 4L, 4L, 
4L, 6L, 6L, 1L), .Label = c("BN", "BS", "GN", "GS", "SB", "SL"
), class = "factor"), Season = c(1981L, 1981L, 1981L, 1981L, 
1995L, 1995L, 1995L, 1997L, 1997L, 2000L), Agrostis.magellanica = c(0.3, 
0.3, 0.3, 0.01, 0.6, 0.3, 0.3, 0.3, 0.6, 0.05), Festuca.contracta = c(0.6, 
0.05, 0.3, 0.01, 0.01, 0, 0, 0, 0.01, 0.05), Poa.annua = c(0.01, 
0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.05, 0.01, 0.01)), .Names = c("Location", 
"Season", "Agrostis.magellanica", "Festuca.contracta", "Poa.annua"
), class = c("data.table", "data.frame"), row.names = c(NA, -10L
)

【问题讨论】:

    标签: r for-loop plot lattice


    【解决方案1】:

    这在 R-FAQ 中。在函数内部使用时需要围绕网格图形(格子或 ggplot)的 print 语句,而 for 循环是一个函数:

    # Needed
    require(data.table)  # before defining the object.
    
    pdf()  # pdf is a multipage device.
    for (i in 3:5) {
      # generate a list of mean value by season for the species in column number i
      temp <- v2[, lapply(.SD, mean), by=c("Season", "Location"), .SDcols=i]
      # Each group in a separate mini plot
      print( xyplot(temp[[3]]~temp[[1]] | temp[[2]], main = colnames(temp)[3]) )
    }
    dev.off()  # Failing to properly close a file graphics device is common error.
    

    【讨论】:

    • 谢谢!请注意,您需要命名 pdf 文件,否则它不会写入,例如pdf("test.pdf") 应该在原始帖子中说明我是在 eps 输出之后,使用您的代码我将 pdf() 替换为 postscript(onefile = FALSE, "Species%03d.eps") 以将多个 eps 文件导出到工作目录。
    • 我们的经历不同。在我的机器上,pdf 文件有一个默认名称“Rplots.pdf”(在 ?pdf 的“使用”部分中描述),所以我不需要提供名称参数。如果您的?pdf 帮助页面不同,请务必注意它的建议。
    • 确实有一个默认名称“RPlots.pdf”。我忽略了工作目录中的那个文件。
    猜你喜欢
    • 1970-01-01
    • 2019-08-29
    • 2020-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-14
    • 2019-12-29
    相关资源
    最近更新 更多