user17491022
user17491022

Reputation: 3

Making multiplot with for loop in ggplot2

i was making a plot with 15 plots in it. I tried par() but it seems that it doesn't work in a loop (or maybe I don't know how)

Here's my code:

vecB <- df2[,17:31]
for (i in seq_along(vecB)){
  print(ggplot(vecB, aes(unlist(vecB[, i]), stat = "count")) +
          geom_bar(width = 0.65,
                   fill = "cadetblue3") +
          geom_text(stat = 'count', aes(label = ..count..),
                    vjust = -0.5, size = 3) +
          scale_y_continuous(limits = c(0, 225)) +
          scale_x_continuous(limits = c(0.5, 5.5)) +
          theme_light() +
          labs(x = paste('B', i, '作答分數'),
               y = '次數')
  )
}

I was wondering if there's a way to make a multiplot with a for loop. Thank you very much!

Upvotes: 0

Views: 172

Answers (2)

maarvd
maarvd

Reputation: 1284

Lacking some sample data, but I suggest you look into pivot_longer in combination with facet_wrap

#select some columns of the iris dataset
dt <- iris[,1:4]

#from wide to long
dt <- tidyr::pivot_longer(dt, cols = names(dt))

#plot, using facet wrap on name
ggplot(dt, aes(x = value)) + geom_bar(stat = "count") + facet_wrap(~name) + theme_bw()

plot

Upvotes: 0

Basti
Basti

Reputation: 1763

Inspired from @MSR answer in this post : Create a collection of plots inside of a `for` loop

You could replace the for loop with a simple lapply and plot all of your ggplots with the ggarrange function

library(ggpubr)
library(tidyverse)

make_plot <- function(n) {
  ggplot(vecB, aes(unlist(vecB[, n]), stat = "count")) +
    geom_bar(width = 0.65,
             fill = "cadetblue3") +
    geom_text(stat = 'count', aes(label = ..count..),
              vjust = -0.5, size = 3) +
    scale_y_continuous(limits = c(0, 225)) +
    scale_x_continuous(limits = c(0.5, 5.5)) +
    theme_light() +
    labs(x = paste('B', n, '作答分數'),
         y = '次數')

}
plots <- lapply(seq_along(vecB), make_plot)

ggarrange(plotlist = plots)

Upvotes: 1

Related Questions