geom_segment() 不存储在 for 循环中定义的对象值

geom_segment() doesn't store object value defined inside a for loop

我定义了一个非常简单的 for 循环,我在其中绘制了一个正态分布,其中有一条垂直的红线和一条较小的垂直黑色线段。正态分布不会改变,但垂直线和垂直线段的位置应该在每次迭代时改变。
如果在每次迭代后即时绘制 ggplot() 对象,线条会正确显示,但是 如果我将每个图存储在列表中然后绘制列表,垂直黑色段始终最后一个循环中定义的值。请检查以下代表:

set.seed(seed = 314159)

library(ggplot2)

plots_list <- list()

for (number in c(1:10)) {

  line <- number
  segment <- number + 1

  p <- ggplot(data = data.frame(x = c(-3, 3)),
              aes(x)) +
    stat_function(fun = dnorm,
                  n = 101,
                  args = list(mean = 0,
                              sd = 1)) +
    geom_vline(xintercept = line,
               colour = "red",
               size = 0.5,
               linetype = "dashed") +
    geom_segment(aes(x = segment,
                     xend = segment,
                     y = 0,
                     yend = 0.5),
                 linetype = "dashed")

  plot(p)

  plots_list[[number]] <- p

}

plots_list

如果您在启动 plot_list 对象后检查绘图,您会看到红线会改变每个绘图的位置,而黑色线段则不会。关于如何解决这个问题的任何建议?谢谢!

你必须拿出aes()

原来的geom_segment()调用是蓝色的。 annotate() 的注释掉的代码与没有 aes()geom_segment() 相同。

set.seed(seed = 314159)

library(ggplot2)

plots_list <- list()

for (number in c(1:10)) {
  line <- number
  segment <- number + 1
  
  p <- ggplot(data = data.frame(x = c(-3, 3)),
              aes(x)) +
    stat_function(fun = dnorm,
                  n = 101,
                  args = list(mean = 0,
                              sd = 1)) +
    geom_vline(xintercept = line,
               colour = "red",
               size = 0.5,
               linetype = "dashed") +
    geom_segment(x = segment,           # the new segment is black
                 xend = segment,
                 y = 0,
                 yend = 0.5,
                 linetype = "dashed") +
    geom_segment(aes(x = segment,       # your original segment is blue
                     xend = segment,
                     y = 0,
                     yend = 0.5),
                 linetype = "dashed",
                 col = "blue")
    # annotate("segment",        # this works, too
    #          x = segment,
    #          xend = segment,
    #          y = 0,
    #          yend = 0.5,
    #          linetype = "dashed",
    #          col = "orange")
  
  plot(p)
  
  plots_list[[number]] <- p
}

plots_list