-2

My question is about using a for loop to repeat data analysis based on a categorial variable.

Using the built in Iris data set how would I run a for loop on the code below so it first produces this chart for just setosa and then versicolor and then virginica without me having to manually change/set the species?

ggplot(iris, aes(Sepal.Length, Sepal.Width)) +
  geom_point()

I'm just starting out and have no idea what I'm doing

DanY
  • 5,920
  • 1
  • 13
  • 33
  • 3
    Do you need to do it in a loop? Could you use `ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point() + facet_wrap(~Species)`? – jared_mamrot Feb 10 '23 at 05:24

2 Answers2

0

You need to use print() as described here

library(tidyverse)
data(iris)

species <- iris |> distinct(Species) |> unlist()

for(i in species) {
  p <- iris |> 
    filter(Species == i) |> 
    ggplot() + 
      geom_point(aes(x=Sepal.Length, y=Sepal.Width)) + 
      ggtitle(i)
  print(p)
}
DanY
  • 5,920
  • 1
  • 13
  • 33
0

You can use a for loop as u/DanY posted; however, it's harder to store and retrieve plots in a universal way with that structure. Running the loop code makes it difficult to retrieve any one particular plot - you would only see the last plot in the output window and have to go "back" to see the others. I would suggest using a list structure instead to allow you to retrieve any one of the individual plots in subsequent functions. For this, you can use lapply() rather than for(...) { ... }.

Here's an example which uses dplyr and tidyr:

library(ggplot2)
library(dplyr)
library(tidyr)

unique_species <- unique(iris$Species)

myPlots <- lapply(unique_species, function(x) {
  ggplot(
    data = iris %>% dplyr::filter(Species == x),
    mapping = aes(x=Sepal.Length, y=Sepal.Width)
  ) +
  geom_point() +
  labs(title=paste("Plot of ", x))
})

You then have the plots stored within myPlots. You can access each plot via myPlots[1], myPlots[2] or myPlots[3]... or you can plot them all together via patchwork or another similar package. Here's one way using cowplot:

cowplot::plot_grid(plotlist = myPlots, nrow=1)

enter image description here

chemdork123
  • 12,369
  • 2
  • 16
  • 32