【发布时间】:2015-12-26 05:19:55
【问题描述】:
我在 R 中使用密度函数,然后根据获得的密度计算一些结果。之后,我使用 ggplot2 显示相同数据的 PDF。
但是,结果与相应图中显示的结果略有不同 - 这可以通过直接绘制密度输出(使用 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))
图片:
【问题讨论】:
-
他们似乎为径向基函数内核使用了不同的带宽。如果希望它们相同,则需要指定相同的带宽
-
是的,您在自己计算密度时会更改默认值,但在使用 geom_density 时不会。
标签: r plot ggplot2 probability-density