1

I am trying to plot multiple "ggplot" in the same page using for loop. The for loop is used because the number of the plots is non-determined "dynamic". The x-axis of the plots will be changed within each iteration. I read so many articles about creating an empty list then add each plot in specific index of the list, then use "multiplot" function to display all the plots of the list in one page. However, This not working !! The problems is the program ends-up by printing only the last plot information saved at the last index of the list with different labels! the code and the figure below indicates the idea. `

Howmany <- readline(prompt="Specify the number of the independent variables: ") 
Howmany <- as.numeric(Howmany)
plot_lst <- vector("list", length = Howmany) #' an empty list
   for ( i in 1:Howmany){
        plot_lst[[i]] <- ggplot(data=data, aes(x=data[, c(i)], y=data$gender))  +
        geom_point(aes(size = 5)) +    
           scale_color_discrete(name = "dependent_variable" + labs(
            title = (paste("Logistic Regression Fitting Model",i)), 
            x = names(data)[i],
            y =  "gender")
        
   }
 multiplot(plotlist = plot_lst, cols = 1)

The output of the code is provided here

I really appreciate any suggestion.

I also tried what were suggested in this link: show multiple plots from ggplot on one page in r

However, still am facing the same problem.

Deema
  • 15
  • 4
  • 1
    I think you need to `print()` the plot object. For example, `p <- ggplot(data = data, aes(....)); print(p)` inside the `for` loop. It may not produce anything, but while knitting your plots will show up. – monte Nov 21 '22 at 05:33
  • While I don't think it's causing your issue, you can remove this: `i = i + 1`. You don't need to manually increment the index `i` since you're using the `for()` construction. You also need to print the plots somehow. I assume you're passing your `plot_lst` list to a `multiplot` function? – Stewart Macdonald Nov 21 '22 at 05:41
  • Without better understanding your data or your code, it's hard to provide much advice. My first suggestion would be to look at pivoting your data to a long format and then using ggplot's facets. If you provide a little bit of sample data we can help you further. – Stewart Macdonald Nov 21 '22 at 05:49
  • Frankly I doubt there is a reason to use for loops in R without an extraordinary reason... For this case: why not to use faceting? http://www.cookbook-r.com/Graphs/Facets_(ggplot2)/ – asd-tm Nov 21 '22 at 06:58
  • yes i am passing it. I edited the question and added the code. what does print do with my problem? does it help ?@StewartMacdonald – Deema Nov 21 '22 at 16:12
  • my data is about doing a logistic regression between a categorical dependent variable and number of independent variables taken from user. the regression part is done. However, i would like to plot all the correlations between the dependent variable and independent variables in one page (each takes one plot), then plot the predict model in one plot. the facet is working will if i have two x-axis variables, but i might have more. @StewartMacdonald – Deema Nov 21 '22 at 16:26

1 Answers1

1

Because ggplot's aes() is using lazy evaluation you need to force evaluation in each iteration of the loop (otherwise all plots will be the same on the last position of i).

One way to do this is by wrapping the righthand side of the assignment in local() and use i <- i:

The labs(x = ...) seemed not to be correct so I rewrote it as: x = names(data)[i], please check if that works for you.

plot_lst <- vector("list", length = Howmany) #' an empty list
for (i in 1:Howmany) {
  
  plot_lst[[i]] <- local({
    i <- i 
    
    ggplot(data=data, aes(x=data[, c(i)], y=data$gender)) +
    geom_point(aes(size = 5)) +    
    scale_color_discrete(name = "dependent_variable") +
      labs(
        title = (paste("Logistic Regression Fitting Model", i)), 
        x = names(data)[i],
        y = "gender")
    })
}

Below is one example using the iris data set. If we print plot_lst we can see three different plots.

I assume the function multiplot is from the scatter package, which is not working with the latest R version, so I can't reproduce if this is working correctly.

Howmany <- readline(prompt="Specify the number of the independent variables: ") 
Howmany <- as.numeric(Howmany)
plot_lst <- vector("list", length = Howmany) #' an empty list

for ( i in 1:Howmany){
  
  plot_lst[[i]] <- local({ 
    i <- i
    
    ggplot(data  = iris,
           aes(x = iris[, c(i)],
               y = iris$Species)) +
    geom_point(aes(size = 5)) +    
    scale_color_discrete(name = "dependent_variable") +
    labs(
      title = paste("Logistic Regression Fitting Model", i), 
      x = names(data)[i],
      y =  "species"
    )
    
  })
}

plot_lst
TimTeaFan
  • 17,549
  • 4
  • 18
  • 39
  • thank you for your answer. However, i tried it and still getting the same output (same problem) @TimTeaFan – Deema Nov 21 '22 at 16:27
  • Can you please provide some example data that allows us reproducing your problem. – TimTeaFan Nov 21 '22 at 19:20
  • to perform logistic regression a user can choose one column as dependent variable. in the presented case, "gender", and choose the numbers and names of independent variables. in the presented case, (math_score, reading_score and lunch) from selected data-frame . Then, I created new data-frame with only the selected columns, where the dependent variable will be the first col and the rest are independent variables. Then, glm( data[, c(1)] ~. , data = d). Then i need to plot the fitted model and the correlation between dependent and independents variables in one page or one plot. @TimTeaFan – Deema Nov 22 '22 at 05:14
  • @Deema: without having your data (use `dput(data)` or if too big a subset of that data) it is hard to reproduce your problem. Please read about how to create a minimal reproducible example. I updated my answer with a simple example from the iris data set. Just use 3 as `Howmany`. When we plot `plot_lst` we see three different plots, but only when using `local({i <- i; .... })`. – TimTeaFan Nov 22 '22 at 06:33