1

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]])
}
4
  • 1
    You need to provide the function for myplot, the data frames df1, df2, df3 in order to make this a sound question. Commented Oct 11, 2017 at 11:25
  • the post has been updated Commented Oct 11, 2017 at 11:44
  • 1
    what is myplot? it is not part of ggplot Commented Oct 11, 2017 at 11:51
  • try this: myplot[i] Commented Oct 11, 2017 at 11:58

1 Answer 1

3

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]))
}
Sign up to request clarification or add additional context in comments.

1 Comment

how can I get names title names, not just names dataframes, assuming they are different

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.