是否可以对 ggplot stat_function 进行动态调用?

Is it possible to do Dynamic Call to ggplot stat_function?

这是如何在混合高斯模型上绘制 ggplot 曲线的一些片段

ggplot(mix_example) + geom_histogram(aes(x = x, y = ..density..)) + 
  stat_function(geom = "line", fun = fun_prop, color="red",
                args = list(mean = comp_1[1], sd = comp_1[2], 
                proportion = proportions[1])) +
  stat_function(geom = "line", fun = fun_prop, color="green",
                args = list(mean = comp_2[1], sd = comp_2[2], 
                proportion = proportions[2]))+
  stat_function(geom = "line", fun = fun_prop, color="blue",
                args = list(mean = comp_3[1], sd = comp_3[2], 
                proportion = proportions[3]))

上面的代码片段添加了 3 个统计函数来绘制混合分布密度上的聚类线,参数 (args) 来自 flexmix 模型,其中包含 每个混合分布簇的均值和标准差,我想将其扩展到“n度”,以便它适用于绘制 n行n簇混合分布。但我想知道有没有什么方法可以不一个一个地添加 stat_function

ggplot2 中有一个名为 ggplot_add.list 的 S3 方法 ggplot_add(负责如何添加 elements/layers)。这会将列表的每个元素添加到绘图中。所以你可以写一个包装器:

multi_stat <- function(.obj, .prop, .color){
  mapply(function(x, prop, color){
    stat_function(
      geom = "line",
      fun = fun_prop,
      color = color,
      args = list(mean = x[1], sd = x[2], proportion = prop))},
    x = .obj, prop = .prop, color = .color, SIMPLIFY = F)
}
      

ggplot(mix_example) + 
  geom_histogram(aes(x = x, y = ..density..)) +
  multi_stat(list(comp_1, comp_2, comp_3),
             proportions,
             c("red","green","blue"))