【问题标题】:R: How to add normal distributions to overlapping grouped histograms with latticeR:如何将正态分布添加到具有格子的重叠分组直方图
【发布时间】:2024-11-30 11:05:01
【问题描述】:

我一直在寻找使用 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

【问题讨论】:

    标签: r histogram distribution lattice


    【解决方案1】:

    这是我能得到的最接近的。我使用的提示是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")
                          }
    
                        }       
                          )
    

    【讨论】:

      最近更新 更多