在多个数据帧上循环使用已定义的ggplot函数

时间:2017-10-11 11:03:07

标签: r loops dataframe

我想创建一个循环来绘制R中多个数据帧的数据,使用一个名为myplot的预先存在的ggplot函数。

我的ggplot函数被定义为myplot,我唯一想要提取的是标题。我知道有类似的帖子,但没有提供预先存在的ggplot函数的解决方案。

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")

这是我的尝试:

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

1 个答案:

答案 0 :(得分:2)

您可以使用预定义函数myplot()在循环中创建多个ggplots,如下所示:

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

如果您想使用2个向量来提供数据框和标题的名称,您可以执行以下操作:

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]))
}
相关问题