【问题标题】:Creating a list of ggplots in a loop, using the index of the loop as an argument to the geom function [duplicate]在循环中创建一个ggplot列表,使用循环的索引作为geom函数的参数[重复]
【发布时间】:2023-04-05 12:04:01
【问题描述】:

这个循环创建了一个包含 3 个 ggplots 的列表,但是因为 xxend 的参数取决于循环的索引,因此感到沮丧:

DF <- data.frame(column1=c(1,2,3,4,5), column2=c(4,5,6,7,8))

list_of_ggplots <- list()

for (num in seq(1:3)){ 
  p <- ggplot()
  p <- p + geom_segment(data=DF, aes(x=column1[num], xend=column2[num], y=1, yend=1))

  list_of_ggplots[[num]] <- p }
list_of_ggplots

我们得到 3 个图基本上是相同的图(因为在它们被调用的时间点,num 是 3)。

创建这些情节的更好策略是什么?

【问题讨论】:

  • 你想让这个没有循环吗?
  • 可以更改/更改/删除循环结构,只要它基本上做同样的事情...动态创建可变数量的绘图,其中给出了用于访问数据框中数据的索引基于对 seq(1:n) 的迭代。或者相当于 seq(1:n) 的东西。
  • 这可以帮助link
  • aes 替换为aes_q 并直接传递值:aes_q(x=DF$column1[num], xend=DF$column2[num], y=1, yend=1)
  • 他/她的问题是需要在同一页面上显示多个图。我的问题围绕着什么时候评估 ggplot 中的表达式。有一些相似之处,但至少解决方案是完全不同的。分面包装和布局问题在我的问题的解决方案中没有任何作用,也不是问题,也不会解决我的问题。无论如何,“这个问题在这里已经有了答案:”根本不是这样的。

标签: r for-loop ggplot2


【解决方案1】:

您可以使用lapply 获得一个列表而无需运行显式循环:

list_of_ggplots <- lapply(1:nrow(DF), function(i) {ggplot(DF[i,]) + aes(x=column1, xend=column2, y=1, yend=1)+geom_segment()})

【讨论】:

    【解决方案2】:

    您可以使用lapply 以更像“R”的方式创建列表,然后使用numDF 子集化,而不是尝试在美学上这样做。但是,您还应该使用scale_x_continuous 并设置limits,否则它们仍然“看起来”相同(除了x 轴上的#)

    list_of_ggplots <- lapply(1:nrow(DF), function(num) {
      p <- ggplot()
      p <- p + geom_segment(data=DF[num,], aes(x=column1, xend=column2, y=1, yend=1))
      p + scale_x_continuous(limits=c(0, max(DF$column2))) 
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-11
      • 2014-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-11
      • 1970-01-01
      相关资源
      最近更新 更多