user2904120
user2904120

Reputation: 416

Loop with a defined ggplot function over multiple dataframes

I would like to make a loop to plot data from multiple dataframes in R, using a a pre-existing ggplot function called myplot.

My ggplot function is defined as myplot and the only things I'd like to extract are titles. I know there are similar posts, but none provides a solution for a pre-existing ggplot function.

df1 <- diamonds[1:30,] 
df2 <- diamonds[31:60,]
df3 <- diamonds[61:90,]

myplot <- ggplot(df1, aes(x = x, y = y)) +
geom_point(color="grey") +
labs(title = "TITLE")

list <- c("df1","df2","df3")
titles <- c("df1","df2","df3")

Here is my try:

for (i in list) {
  myplot(plot_list[[i]])
  print(plot_list[[i]])
}

Upvotes: 1

Views: 1684

Answers (1)

Patrik_P
Patrik_P

Reputation: 3200

You can create multiple ggplots in a loop with predifined function myplot() as follows:

list <- c("df1","df2","df3") #just one character vector as the titles are the same as the names of the data frames

myplot <- function(data, title){
  ggplot(data, aes(x = x, y = y)) +
    geom_point(color="grey") +
    labs(title = title)
}

for(i in list){
  print(myplot(get(i), i))
}

If you wanna work with 2 vectors giving the names if the data frames and of the titles you can do the following:

list <- c("df1","df2","df3")
titles <- c("Title 1","Plot 2","gg3") 

myplot <- function(data, title){
  ggplot(data, aes(x = x, y = y)) +
    geom_point(color="grey") +
    labs(title = title)
}

for(i in seq_along(list)){ #here could also be seq_along(titles) as they a re of the same length
  print(myplot(get(list[i]), titles[i]))
}

Upvotes: 3

Related Questions