0

I'm trying to automate the generation of several segmented bar plots. There are thirteen variables that I'm trying to loop over, named as per the following convention: mc_q#. I'm trying the following code, but all it does is generate a plot called px and then stop running:

for (x in 1:13) {
px <- ggplot(tct_tqi, 
             aes(x = mc_qx, 
                 fill = test_category)) + 
  geom_bar(position = "fill") +
  labs(fill="TCT mark band")
}

Will be grateful for any help!!

1 Answer 1

2

You may create a list of plots -

library(ggplot2)

variables <- paste0('mc_q', 1:13)
result_px <- vector('list', length(variables))

for (i in seq_along(variables)) {
  result_px[[i]] <- ggplot(tct_tqi, 
            aes(x = .data[[variables[i]]], fill = test_category)) + 
    geom_bar(position = "fill") +
    labs(fill="TCT mark band")
}

result_px[[1]] would return the 1st plot, result_px[[2]] the 2nd plot and so on.

Sign up to request clarification or add additional context in comments.

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.