是否可以对 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",color="green",args = list(mean = comp_2[1],sd = comp_2[2],proportion = proportions[2]))+
  stat_function(geom = "line",color="blue",args = list(mean = comp_3[1],sd = comp_3[2],proportion = proportions[3]))

enter image description here

上面的 Snippets 添加了 3 个 stat 函数来绘制混合分布密度上的聚类线,参数(args)来自 flexmix 模型包括 均值和标准差 > 对于每个混合分布簇,我想将其扩展到 “n 度”,以便它适用于绘制 n 条混合分布簇的 n 行。但是不知道有没有什么办法可以不用一一添加stat_function

解决方法

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

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"))