R:如何将正态分布添加到具有晶格的重叠分组直方图中

时间:2015-12-03 20:46:07

标签: r histogram distribution lattice

我一直在寻找使用函数'直方图'重叠分组直方图的方法。在格子里,我找到了here的答案。

histogram( ~Sepal.Length,
 data = iris,
 type = "p",
 breaks = seq(4,8,by=0.2),
 ylim = c(0,30),
 groups = Species,
 panel = function(...)panel.superpose(...,panel.groups=panel.histogram,
                      col=c("cyan","magenta","yellow"),alpha=0.4),
 auto.key=list(columns=3,rectangles=FALSE,
               col=c("cyan","magenta","yellow3"))
 )

现在我的问题是你是否还可以为这个情节添加每个组的正态分布。

可能使用这个?

panel.mathdensity(dmath = dnorm, col = "black",
              args = list(mean=mean(x),sd=sd(x)))

最终结果应该看起来与此类似: image

1 个答案:

答案 0 :(得分:0)

这是我能得到的最接近的。我使用的提示是here。我的问题是密度图隐藏在下一个直方图之后。

plot1 <- histogram( ~Sepal.Length,
                    data = iris,
                    type = "p",
                    ylim = c(0,30),
                    breaks = seq(4,8,by=0.2),
                    groups = Species,
                    col=c("cyan","magenta","yellow"),
                    panel = panel.superpose,
                    panel.groups = function(x,y, group.number,...){
                      specie <- levels(iris$Species)[group.number]         
                      if(specie %in% "setosa"){
                        panel.histogram(x,...)
                        panel.mathdensity(dmath=dnorm,args = list(mean=mean(x), sd=sd(x)), col="black")
                      }
                      if(specie %in% "versicolor"){
                        panel.histogram(x,...)
                        panel.mathdensity(dmath=dnorm,args = list(mean=mean(x), sd=sd(x)), col="black")
                      }
                      if(specie %in% "virginica"){
                        panel.histogram(x,...)
                        panel.mathdensity(dmath=dnorm,args = list(mean=mean(x), sd=sd(x)), col="black")
                      }

                    }       
                      )

enter image description here