简体   繁体   English

如何使用ggplot2和晶格在直方图上叠加分布曲线

[英]How to superimpose distribution curves on histograms using ggplot2 and lattice

Say, I am using facet_grid() in ggplot2 to obtain 2 histograms. 说,我在ggplot2中使用facet_grid()来获得2个直方图。 Now I want to superimpose these histograms with Poisson curves (having different means for the 2 histogram plots/grids) and a second curve of another distribution (for which I want to manually provide the probability function of values). 现在我想用泊松曲线(对2个直方图/网格有不同的平均值)和另一个分布的第二条曲线(我想手动提供值的概率函数)叠加这些直方图。 How can this be done? 如何才能做到这一点?

Constructing an example: 构建一个例子:

library(ggplot2)

value<-c(rpois(500,1.5))

group<-rep(c("A","B"),250)

data<-data.frame(value,group)

g1<-ggplot(data,aes(value))

g1+geom_histogram(aes(y=..count..),binwidth=1,position="identity")+facet_grid(.~group)

What next? 接下来是什么?

Alternatively, can it be done using the lattice package? 或者,可以使用晶格封装吗?

The easy way is to plot densities instead of counts and use stat_function() 简单的方法是绘制密度而不是计数并使用stat_function()

library(ggplot2)
value<-c(rpois(500,1.5))
group<-rep(c("A","B"),250)
data<-data.frame(value,group)
ggplot(data,aes(value)) + 
        geom_histogram(aes(y=..density..), binwidth=1,position="identity") + 
        facet_grid(.~group) + 
        stat_function(geom = "line", fun = dpois, arg = list(lambda = 1.5), colour = "red", fill = NA, n = 9)

If you want counts then you need to convert the densities of dpois to 'counts' 如果你想要计数,那么你需要将dpois的密度转换为'计数'

ggplot(data,aes(value)) + 
        geom_histogram(aes(y=..count..), binwidth=1,position="identity") + 
        facet_grid(.~group) + 
        stat_function(geom = "line", fun = function(..., total){dpois(...) * total}, arg = list(lambda = 1.5, total = 250), colour = "red", fill = NA, n = 9)

当最近遇到类似的问题(比较发行版)时,我写了一些透明重叠直方图的代码,可能会给你一些关于从哪里开始的想法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM