0

I have a loop that prints 4 ggplots, but I want to print all 4 in one grid. I have heard people use Multiplot, but I couldn't figure out how to use that within my loop.

This is my working code:

    namesvector <- list("Start", "Week_1", "Week_3", "Week_5")
for (i in 4:ncol(data_3)) {
  print(
    ggplot(data_3, aes(
      y = data_3[, i], x = Biomass, color = Tissue
    )) +
      geom_point() + geom_smooth(method = "lm") +
      labs(title = namesvector[i - 3], x = "Biomass", y = "Isotopic Signature")
  )
  
}

At the moment it prints all 4 plots individually: Example

Par mfrow c(2,2) also doesn't work.

  • With ggplot (not base), since the plots are objects it's generally better to put the plots in a list, and then plot the list of plots at the end. The linked duplicate has several methods for putting them together. – Gregor Thomas Feb 23 '21 at 19:11
  • Alternately, you could probably `pivot_longer` your data and use a single plot with `facet_wrap`. – Gregor Thomas Feb 23 '21 at 19:11
  • One unrelated piece of advice, don't use a `list` when a regular vector will do. `amesvector <- list("Start", "Week_1", "Week_3", "Week_5")` would be better as `amesvector <- c("Start", "Week_1", "Week_3", "Week_5")` – Gregor Thomas Feb 23 '21 at 19:12
  • Thank you @ Gregor Thomas, I think pivot_longer is what i need, but I'm not sure how I would incorporate it. My coding skills arent great. Also thank you for the extra advice, i changed it to a regular vector :) – Matt Heron Feb 23 '21 at 19:27
  • Sounds good - if you need help with `pivot_longer` post a new question that includes some sample data. Something like `dput(data_3[1:5, ])` will make a copy/pasteable version of the first 5 rows of your data. – Gregor Thomas Feb 23 '21 at 19:58

0 Answers0