# Plotting 4 plots with for-loop

Hello, I've got a question about a homework if have got.

The task is: Plot the histogram of the reaction times of the four participants as four plots on one canvas.

This is the data we've got:

simrts <- c(rgamma(500,shape=1,scale=0.1)*12,rgamma(500,shape=1,scale=0.175)*17,rgamma(500,shape=1,scale=0.2)*14,rgamma(500,shape=1,scale=0.3)*10)
rtdat <- data.frame(id = rep(c(1,2,3,4),each=500), rt = simrts)

I know i have to use the loop function but i don't understand quite how. Appreciate every help It looks to me, you may could also use the group_by() and facet_wrap() function with ggplot.

1 Like

Some approaches

``````library(tidyverse)
library(patchwork)

car <- mtcars %>%
as_tibble(rownames = "car")

# approach 1: facet_wrap (or facet_grid)
mtcars %>%
ggplot(aes(x = mpg, y = drat)) +
geom_point() +
facet_wrap(~carb)

# approach 2: patchwork

p1 <- mtcars %>%
filter(carb == 1) %>%
ggplot(aes(x = mpg, y = drat)) +
geom_point()

p2 <- mtcars %>%
filter(carb == 2) %>%
ggplot(aes(x = mpg, y = drat)) +
geom_point()

p3 <- mtcars %>%
filter(carb == 3) %>%
ggplot(aes(x = mpg, y = drat)) +
geom_point()

p4 <- mtcars %>%
filter(carb == 4) %>%
ggplot(aes(x = mpg, y = drat)) +
geom_point()

p6 <- mtcars %>%
filter(carb == 6) %>%
ggplot(aes(x = mpg, y = drat)) +
geom_point()

p8 <- mtcars %>%
filter(carb == 8) %>%
ggplot(aes(x = mpg, y = drat)) +
geom_point()

p1 + p2 + p3 + p4 + p6 + p8

# approach 3: patchwork + forloop
n <- unique(mtcars\$carb)

for(i in n){
assign(paste0("p", i),
mtcars %>%
filter(carb == i) %>%
ggplot(aes(x = mpg, y = drat)) +
geom_point()
)
}
p1 + p2 + p3 + p4 + p6 + p8

``````

Thank you very much, but we should only use the function loop Thank you but the prof told us not to use ggplot so I'll keep on trying Can `par(mfrow=c(2,2))` be useful? Quick-R: Combining Plots

What a prof. does this?!

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.