【问题标题】:R plot density ggplot vs plotR绘图密度ggplot与绘图
【发布时间】: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


【解决方案1】:

当前 cmets 正确识别出您正在使用两种不同的带宽来计算两个绘图中的密度:plot() 图表使用您指定为带宽的bwidthggplot() 图表使用默认带宽。理想情况下,您会将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),因此您可以在 stat_density (stat_density documentation) 中指定 adjust 值,以尝试尝试调整 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

【讨论】:

  • 你是对的,谢谢!我正在使用从所有样本中获得的 bw(即 0.5902679)并在图中强制使用它。但是,我正在绘制两条曲线(来自样本数据的组)。如果未指定 bw,则绘图使用两组中较低的带宽 (0.1232133)。因此,似乎adjust = 0.5902679/0.1232133 = 4.79062,或者: adj = bwidth / min((density ( sample[[1]] ))$bw, (density ( sample[[2]] ))$bw)跨度>
猜你喜欢
  • 2014-08-20
  • 1970-01-01
  • 1970-01-01
  • 2014-10-08
  • 2014-06-19
  • 1970-01-01
  • 2016-07-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多