0

这是如何在混合高斯模型上绘制 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]))

在此处输入图像描述

上面的 Snippets 添加了 3 个 stat 函数以在混合分布密度上绘制一条集群线,参数 (args) 来自flexmix 模型,该模型由每个混合分布集群的均值和标准差组成,我想将其扩展为“ n 度”,因此它适用于绘制n 条混合分布的 n 簇的 n 条线。但我想知道是否有任何方法可以在不一一添加 stat_function 的情况下做到这一点

4

1 回答 1

2

ggplot2一个 S3 方法ggplot_add(负责如何添加元素/层)称为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"))
  
于 2021-05-17T16:35:32.833 回答