R图密度GG图vs图
我在R中使用密度函数,然后根据得到的密度计算一些结果。之后,我使用ggplot2显示相同数据的PDF 但是,结果与相应绘图中显示的结果略有不同,这是通过直接绘制密度输出(使用绘图{graphics})得到证实的 知道为什么吗?我如何更正它,使结果和绘图(来自ggplot2)完全匹配/来自相同的数据 这方面的示例(代码和图像):R图密度GG图vs图,r,plot,ggplot2,probability-density,R,Plot,Ggplot2,Probability Density,我在R中使用密度函数,然后根据得到的密度计算一些结果。之后,我使用ggplot2显示相同数据的PDF 但是,结果与相应绘图中显示的结果略有不同,这是通过直接绘制密度输出(使用绘图{graphics})得到证实的 知道为什么吗?我如何更正它,使结果和绘图(来自ggplot2)完全匹配/来自相同的数据 这方面的示例(代码和图像): srcdata=data.frame(“值”=c(4.6228、1.7942、4.2738、2.1502、2.2665、5.1717、4.1015、2.5126、4.42
srcdata=data.frame(“值”=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),“类型”=c(“正”、“负”、“负”、“正”、“负”、“正”、“负”,“负”、“负”、“负”、“正”、“正”、“负”、“正”、“负”、“正”、“负”))
bwidth当前注释正确识别您正在使用两种不同的带宽来计算两个图中的密度:plot()
图形使用您指定为带宽的bwidth
和ggplot()
graph使用默认带宽。理想情况下,您可以将bwidth
传递到ggplot graph,这将解决所有问题,但是围绕SO问题的注释表明,您不能将带宽参数传递到stat\u density
或geom\u density
要在两个图中获得相同的输出,最简单的方法是让density()
在手动密度计算(如下)和ggplot图(使用您已有的相同代码)中确定最佳带宽
编辑
如果您想特别调整ggplot图,使其使用bwidth
变量作为密度平滑中的binwidth,您可能会发现此问题的答案很有用:它们似乎对径向基函数内核使用了不同的带宽。如果您希望它们相同,则需要指定相同的带宽dthYes,您在自己计算密度时更改了默认值,但在使用geom_密度时没有更改。您是对的,谢谢!我使用的是从所有样本中获得的bw(即0.5902679),并在绘图中强制使用。但是,我正在绘制两条曲线(从样本数据中分组)。如果未指定bw,则绘图使用两组中较低的带宽(0.1232133)。因此,它似乎调整=0.5902679/0.1232133=4.79062,或:adj=宽度/分钟((密度(样本[[1]]))$bw,(密度(样本[[2]])$bw)
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))
densities <- lapply ( sample, density, n = 512, from = xmin, to = xmax )
ggplot(data = srcdata, aes(x=Value)) +
geom_density(aes(group=Type, colour=Type), adjust = 4.5) +
xlim(xmin, xmax)