Adam_G
Adam_G

Reputation: 7879

Create individual plots for each column

I have a dataframe similar to df below. For each factor, I'd like to create a boxplot comparing that factor to the final score. Without a loop, it looks like the code below. In practice, I want to do this for 40 columns, and display it in a grid. Some sort of looping through columns seems appropriate here, but I'm unsure how to do that.

library(ggplot2)
library(gridExtra)

scores <- c(97, 98, 90, 92)
factor1 <- c(1, 0, 0, 1)
factor2 <- c(2, 1, 2, 0)
factor3 <- c(0, 0, 0, 1)

df <- data.frame(scores, factor1, factor2, factor3)

plot1 <- ggplot(df, aes(x=factor(factor1), y=scores)) + geom_boxplot()
plot2 <- ggplot(df, aes(x=factor(factor2), y=scores)) + geom_boxplot()
plot3 <- ggplot(df, aes(x=factor(factor3), y=scores)) + geom_boxplot()
grid.arrange(plot1, plot2, plot3, ncol=2)

Upvotes: 0

Views: 59

Answers (1)

Marco Sandri
Marco Sandri

Reputation: 24252

library(ggplot2)
library(gridExtra)

df <- data.frame(scores=c(97, 98, 90, 92), factor1=c(1, 0, 0, 1), 
                 factor2=c(2, 1, 2, 0),  factor3=c(0, 0, 0, 1))

fun <- function(x) {
   dts <- df[,c("scores",x)]
   names(dts)[2] <- "varx"
   p <- ggplot(dts, aes(x=factor(varx), y=scores)) + geom_boxplot() + xlab(x)
   return(p)
}

ps <- lapply(names(df)[-1], fun)
grid.arrange(grobs=ps, ncol=2)

enter image description here

Upvotes: 1

Related Questions