R绘制密度图:ggplot与plot的区别

3

我正在使用 R 中的密度函数并计算一些从获得的密度中得出的结果。之后,我使用 ggplot2 显示相同数据的概率密度函数。

然而,结果与相应图形中显示的结果略有不同 - 这通过直接绘制密度输出(使用 plot {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))

图片:

这里输入图片描述


这是一个关于IT技术的图片。

3
他们似乎在使用不同的径向基函数核带宽。如果你想让它们相同,你需要指定相同的带宽。 - alexwhitworth
1
是的,当你自己计算密度时,你正在改变默认值,但是在使用geom_density时并没有改变。 - Axeman
1个回答

3
当前的评论正确地指出,您在两个图中使用了两种不同的带宽来计算密度:`plot()` 图表使用您指定的 `bwidth` 作为带宽,而 `ggplot()` 图表使用默认带宽。理想情况下,您应该将 `bwidth` 传递给 ggplot 图表,这样就可以解决所有问题,然而 SO 问题here周围的评论表明,您无法将带宽参数传递给 `stat_density` 或 `geom_density`。
为了在两个图中获得相同的输出,最简单的方法是让 `density()` 在您的手动密度计算(如下所示)和 ggplot 图表中确定最佳带宽(使用您已经拥有的相同代码)。
densities <- lapply ( sample, density, n = 512, from = xmin, to = xmax )

另外,geom/stat_density中实际使用的binwidth是预定的binwidth乘以adjust参数 (参见 density documentation),因此您可以在stat_density中指定一个adjust值(参见stat_density documentation)尝试调整ggplot的binwidth以匹配您的bwidth变量。我发现一个adjust值为4.5给出了一个类似(但不完全相同)于原始图形的版本,该版本使用了您计算出的密度值:

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

Adjusted ggplot density graph

编辑:如果您想要特别调整您的ggplot图形,使其使用您的bwidth变量作为密度平滑中的binwidth,则可以在此问题的答案中找到有用的信息:理解ggplot2中的带宽平滑


你说得对,谢谢! 我之前使用了从所有样本中获得的bw(为0.5902679),并将其强制用于绘图。然而,我正在绘制两条曲线(来自样本数据的两个组)。如果没有指定bw,则绘图将使用两个组中较小的带宽(0.1232133)。因此,似乎需要进行调整= 0.5902679 / 0.1232133 = 4.79062,或者: adj = bwidth / min((density ( sample[[1]] ))$bw, (density ( sample[[2]] ))$bw) - Panda

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接