0

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!

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.