2

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

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对象后检查绘图,您会看到每个绘图的红线位置发生变化,而黑色线段则没有。关于如何解决这个问题的任何建议?谢谢!

4

1 回答 1

1

你必须拿出来aes()

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

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

在此处输入图像描述

于 2021-10-05T15:59:22.497 回答