【问题标题】:Loop with a defined ggplot function over multiple dataframes在多个数据帧上使用定义的 ggplot 函数循环
【发布时间】:2018-03-23 00:47:43
【问题描述】:

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

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

【问题讨论】:

  • 您需要为 myplot 提供函数,数据框 df1、df2、df3 才能使这个问题成为一个合理的问题。
  • 帖子已更新
  • 什么是myplot?它不是 ggplot 的一部分
  • 试试这个:myplot[i]

标签: r loops dataframe


【解决方案1】:

您可以使用预定义函数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]))
}

【讨论】:

  • 如何获取名称标题名称,而不仅仅是名称数据框,假设它们不同
猜你喜欢
  • 1970-01-01
  • 2021-05-09
  • 1970-01-01
  • 1970-01-01
  • 2017-05-06
  • 2021-12-02
  • 1970-01-01
  • 1970-01-01
  • 2019-11-15
相关资源
最近更新 更多