ggplot graphs in a loop across several predictor variables

I have a binary outcome and several predictors. I need a series of ggplots and would rather not have to type them all out. I just finished figuring out how to loop glm's, but ggplot is giving me more trouble. How can I do this?


ID outcome x1 x2 x3
1 1 6 Blah Y
2 0 1 Dee N
3 1 3 Bleh N

Tedious code:

p1 = ggplot(data, aes(x = x1, fill = outcome)) + geom_bar(position = "dodge")
p2 = ggplot(data, aes(x = x2, fill = outcome)) + geom_bar(position = "dodge")
p3 = ggplot(data, aes(x = x3, fill = outcome)) + geom_bar(position = "dodge")

Maybe this works?

map(c("x1", "x2", "x3"), function(var){
  ggplot(data, aes_string(x = var, fill = "outcome")) +
    geom_bar(position = "dodge")
1 Like

This topic was automatically closed 7 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.