【问题标题】:R : Create list of plots with for loopR:使用 for 循环创建绘图列表
【发布时间】:2018-12-05 15:44:10
【问题描述】:

我尝试使用 for 循环创建数据图列表以过滤 (="TAB_tmp2") 并在列表中添加新图 (="ListeGRAPH")。我认为问题出在过滤数据表(="TAB_tmp2")的差异。
我已经在网上阅读了几个关于此的主题,但我找不到在这种情况下可行的解决方案。

我的代码:

rm(list=ls()) # delete objects

#====================================
# Create data for the example 
#====================================  
TAB = data.frame(Types_Mesures = c(rep(1,3),rep(2,5),rep(3,10)))
TAB$ID_mesuresParType=NA
TAB$Mesures=log(c(1:length(TAB$Types_Mesures)))
Nb_Types=length(unique(TAB$Types_Mesures)) # in the real data, the number of "Types_Mesures" can change

for (x in 1:Nb_Types) {
  TAB_tmp=TAB[TAB$Types_Mesures==x,2]
  TAB[TAB$Types_Mesures==x,2]=c(1:length(TAB_tmp)) 
}

#====================================
# List of plots
#====================================
library(gridExtra)
library(ggplot2)

INPUTDirectory= "D:/TEST/"
setwd(dir=INPUTDirectory)

ListeGRAPH <- list()

for (x in 1:Nb_Types) {

  TAB_tmp2=TAB[TAB$Types_Mesures==x,]

  ListeGRAPH[[x]] <- ggplot(data = TAB_tmp2) + 
    geom_line(aes(x = TAB_tmp2$ID_mesuresParType, y = TAB_tmp2$Mesures))

  #   #Save graph
  #   png(filename = paste("TAB_plot_T",x,".png", sep = ""))
  #   print(ListeGRAPH[[x]]) 
  #   graphics.off()

}

gridExtra::grid.arrange(grobs = ListeGRAPH)

当我运行代码时,我有这个错误:

错误:美学长度必须为 1 或与数据相同 (3): x, y

似乎 grid.arrange 不接受不同尺寸的图? 我怎么能用这种表格制作地块列表?在我的真实数据中,“Types_Mesures”的数量可以改变。 此外,我认为 for 循环不允许使用临时变量 (="TAB_tmp2") 来创建绘图列表,但是当我将绘图保存在 PNG 文件中时,此代码有效。

非常感谢您的帮助!

【问题讨论】:

    标签: r


    【解决方案1】:

    问题实际上不在于grid.arrange。当您使用ggplot 创建绘图时,您不需要使用$ 对列进行索引。所以而不是:

    ListeGRAPH[[x]] <- ggplot(data = TAB_tmp2) + 
      geom_line(aes(x = TAB_tmp2$ID_mesuresParType, y = TAB_tmp2$Mesures))
    

    你应该使用:

    ListeGRAPH[[x]] <- ggplot(data = TAB_tmp2) + 
      geom_line(aes(x = ID_mesuresParType, y = Mesures))
    

    然后您将能够使用grid.arrange 绘制结果。

    【讨论】:

    • 感谢您的帮助。该代码有效,但我不得不说我真的不明白为什么它现在有效。事实上,这个合成器:“ggplot(data = TAB_tmp2) + geom_line(aes(x = TAB_tmp2$ID_mesuresParType, y = TAB_tmp2$Mesures))” 当我使用它时也会返回一个正确的图
    猜你喜欢
    • 1970-01-01
    • 2021-01-10
    • 1970-01-01
    • 2017-03-24
    • 1970-01-01
    • 2014-03-31
    • 1970-01-01
    • 1970-01-01
    • 2021-05-25
    相关资源
    最近更新 更多