简体   繁体   中英

R : Create list of plots with for loop

I try to create a list of plots of my data using a for loop to filter (="TAB_tmp2") and add the new plot in the list (="ListeGRAPH"). I think the problem comes from the difference of filter data table (="TAB_tmp2").
I have read several topics on the web about that but I can't find a solution which could works in this case.

My code :

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)

When I run the code, I have this error :

Error: Aesthetics must be either length 1 or the same as the data (3): x, y

It seems that grid.arrange don't accept plots of different dimensions ? How could I do to make the list of plots with this kind of table ? In my real data the number of "Types_Mesures" can change. More over, I think the for loop don't allow to use a temporary variable (="TAB_tmp2") to create the list of plot but this code works when I save my plot in PNG files.

Thanks a lot for you help !

The problem is actually not with grid.arrange . When you're creating the plots with ggplot , you do not need to use $ for indexing of columns. So instead of:

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

you should use:

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

and then you will be able to plot the results using grid.arrange .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM