Loop with a defined ggplot function over multiple dataframes

后端 未结 1 1097
温柔的废话
温柔的废话 2021-01-25 17:25

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

1条回答
  •  情话喂你
    2021-01-25 17:38

    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]))
    }
    

    0 讨论(0)
提交回复
热议问题