【问题标题】:How to add 'stat_function()' layers in ggplot2 using a for loop?如何使用 for 循环在 ggplot2 中添加“stat_function()”层?
【发布时间】:2019-10-28 18:31:36
【问题描述】:

我有几个相似的数据框和每个数据集的非线性回归。只要最初我不知道那里有多少数据框,我就想使用 for 循环覆盖这些图。我可以使用for() 循环覆盖geom_point() 层,但是当我使用stat_function() 尝试相同时,只绘制最后一个函数。

我怎样才能获得与积分相同的功能结果?

MWE:

library(ggplot2)
# Colors vector
hues = seq(15, 375, length = 10 + 1)
cols = hcl(h = hues, l = 65, c = 100)[1:10]

# Create plot and add first layer
p <- ggplot(data = data.frame(x = 1:10, y = 10 + 1:10), 
             aes(x = x, y = y, color = cols[i])) +
      geom_point()

# Add points of other datasets
for (i in 1:9) {
  p <- p + geom_point(data = data.frame(x = 1:10, y = i + 1:10), color = cols[i])   
}
print(p)

# This for cycle only seems to work for the last layer
for (i in 1:10) {
  p <- p + stat_function(fun = function(x) (i + x), color = cols[i]) 
}
print(p)

提前谢谢你。

【问题讨论】:

    标签: r for-loop ggplot2


    【解决方案1】:

    for 循环不会创建环境来为您捕获 i 值。因此,您每次都使用免费变量 i 创建相同的函数,并且在打印绘图之前不会“查找”该值,并且在 for 循环之后 i 的值仅为 10。

    相反,您应该使用args= 命令捕获层中的值。这些将在循环期间进行评估,而不是在绘制时。然后只需将您捕获的变量作为参数添加到函数中。

    for (i in 1:10) {
      p <- p + stat_function(fun = function(x, i) (i + x), color = cols[i], args=list(i=i)) 
    }
    print(p)
    

    【讨论】:

      【解决方案2】:

      在动态添加图层时,我更喜欢将 ggplot 对象视为图层列表,因此这是将图层构建到列表中的问题。你可以使用lapply()purrr::map(),这里我选择后者:

      lines <- purrr::map(1:10, function(y) stat_function(fun = function(x) (y + x), color = cols[y]))
      
      p + lines
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-04
        • 1970-01-01
        • 1970-01-01
        • 2016-07-19
        • 1970-01-01
        相关资源
        最近更新 更多