R图密度ggplot vs plot

R plot density ggplot vs plot

我在 R 中使用密度函数,然后根据获得的密度计算一些结果。之后,我使用ggplot2来显示相同​​数据的PDF。

但是,结果与相应图中显示的结果略有不同 - 通过直接绘制密度输出(使用图 {graphics})可以确认这一点。

知道为什么吗?我该如何更正它,以便结果和绘图(来自 ggplot2)匹配/来自完全相同的数据?

这方面的一个例子(代码和图片):

srcdata = data.frame("Value" = c(4.6228, 1.7942, 4.2738, 2.1502, 2.2665, 5.1717, 4.1015, 2.5126, 4.4270, 4.4729, 2.5112, 2.3493, 2.2787, 2.0114, 4.6931, 4.6582, 3.3162, 2.2995, 4.3954, 1.8488), "Type" = c("Positive", "Negative", "Positive", "Negative", "Negative", "Positive", "Positive", "Negative", "Positive", "Positive", "Negative", "Negative", "Negative", "Negative", "Positive", "Positive", "Positive", "Negative", "Positive", "Negative"))

bwidth <- ( density ( srcdata$Value ))$bw

sample <- split ( srcdata$Value, srcdata$Type )[ 1:2 ]

xmin = min(srcdata$Value) - 0.2 * abs(min(srcdata$Value))
xmax = max(srcdata$Value) + 0.2 * abs(max(srcdata$Value))

densities <- lapply ( sample, density, bw = bwidth, n = 512, from = xmin, to = xmax )

#plotting densities result
plot( densities [[ 1 ]], xlim = c(xmin,xmax), col = "steelblue", main = "" )
lines ( densities [[ 2 ]], col = "orange" )

#plot using ggplot2
ggplot(data = srcdata, aes(x=Value)) + geom_density(aes(group=Type, colour=Type)) + xlim(xmin, xmax)

#or with ggplot2 (using easyGgplot2)
ggplot2.density(data=srcdata, xName='Value', groupName='Type', alpha=0.5, xlim=c(xmin,xmax))

图片:

当前的评论正确地指出您正在使用两个不同的带宽来计算两个图中的密度:plot() 图使用您指定的 bwidth 作为带宽,ggplot() 图使用默认带宽。理想情况下,您会将 bwidth 传递给 ggplot 图,这将解决所有问题,但是围绕 SO 问题 here 的评论表明您不能将带宽参数传递给 stat_densitygeom_density

要在两个图中获得相同的输出,最简单的方法是让 density() 确定手动密度计算(下方)和 ggplot 图中的最佳带宽(使用相同的代码已经有)

densities <- lapply ( sample, density, n = 512, from = xmin, to = xmax )

或者,geom/stat_density 中使用的实际 binwidth 是预先确定的 binwidth 乘以调整参数(density documentation) so you could specify an adjust value in stat_density (stat_density documentation),试图调整 ggplot binwidth 以匹配您的 bwidth 变量。我发现 4.5 的调整值给出了与您计算的密度生成的原始图形相似(但不精确)的版本:

ggplot(data = srcdata, aes(x=Value)) + 
    geom_density(aes(group=Type, colour=Type), adjust = 4.5) +
    xlim(xmin, xmax)

编辑 如果您想专门调整您的 ggplot 图,以便它使用您的 bwidth 变量作为密度平滑中的 binwidth,您可能会发现这个问题的答案很有帮助:Understanding bandwidth smoothing in ggplot2