sbac
sbac

Reputation: 2081

How to make a loop to plot several graphs using ggplot

This is my dataframe:

x1 <- c(1,2,3,4)
x2 <- c(3,4,5,6)
x3 <- c(5,6,7,8)
x4 <- c(7,8,9,10)
x5 <- c(8,7,6,5)
df <- c(x1,x2,x3,x4,x5)

I choose 3 variables from my dataframe to plot 3 separate scatterplots each against x1 and store these in a character vector:

varlist <- c("x2","x4","x5")

So I want to create a function to make 3 independent scatterplots of x1 with x2, x1 with x4 and x1 with x5, using ggplot, where xx and yy will be the different pairs of variables to plot:

ggplot(data = df) +
  geom_point(mapping = aes(x = xx, y = yy)) +
  geom_smooth(mapping = aes(x = xx, y = yy))

Upvotes: 0

Views: 105

Answers (1)

Haboryme
Haboryme

Reputation: 4761

You could do:

mapply(function(y) print(ggplot(data = df) +
  geom_point(aes_string(x = "x1", y = y)) +
  geom_smooth(aes_string(x = "x1", y = y))), y=c("x2","x4","x5"))

Note : I used df <- data.frame(x1,x2,x3,x4,x5) instead of df <- c(x1,x2,x3,x4,x5)

x is set to x1, mapply will loop over y which contains the different variables we want to have plotted against x1.

Upvotes: 2

Related Questions