使用定义的ggplot函数在多个数据帧上循环 [英] Loop with a defined ggplot function over multiple dataframes

查看:77
本文介绍了使用定义的ggplot函数在多个数据帧上循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我的ggplot函数定义为myplot和我想提取的唯一内容是标题。我知道也有类似的帖子,但是都没有提供针对现有ggplot函数的解决方案。

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

这是我的尝试:

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


推荐答案

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

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

这篇关于使用定义的ggplot函数在多个数据帧上循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆