2017-10-13 1295 views
1

说我有这个数据帧dfggplot2,直方图:为什么y = ..density ..和stat =“density”有区别?

structure(list(max.diff = c(6.02, 7.56, 7.79, 7.43, 7.21, 7.65, 
8.1, 7.35, 7.57, 9.09, 6.21, 8.2, 6.82, 7.18, 7.78, 8.27, 6.85, 
6.72, 6.67, 6.99, 7.32, 6.59, 6.86, 6.02, 8.5, 7.25, 5.18, 8.85, 
5.44, 6.44, 7.85, 6.25, 9.06, 8.19, 5.08, 6.26, 8.92, 6.83, 6.5, 
7.55, 7.31, 5.83, 5.55, 4.29, 8.29, 8.72, 9.5)), class = "data.frame", row.names = c(NA, 
-47L), .Names = "max.diff") 

我想绘制这是用ggplot2密度的情节:

p <- ggplot(df, aes(x = max.diff)) 
p <- p + geom_histogram(stat = "density") 
print(p) 

赋予,

enter image description here

现在,一个天真的问题:为什么不给出相同的结果?

p <- ggplot(df, aes(x = max.diff)) 
p <- p + geom_histogram(aes(y = ..density..)) 
print(p) 

enter image description here

这是因为所选择的binwidth或数bins或其他一些参数的?到目前为止,我还没有能够调整这些参数来使它们相同。还是我策划了一些完全不同的东西?

回答

0

第二个示例是重新缩放柱状图计数,以使柱状图区域积分为1,但与标准ggplot2柱状图相同。您可以使用binsbinwidth参数调整条数。

第一个例子是计算核密度估计并将输出(每个x值处的估计密度)绘制为直方图。您可以使用参数adjust更改密度估计的平滑量,以及使用参数n计算密度的点的数量。

geom_histogram的默认值为bins=30stat="density"的默认值为adjust=1n=512stat="density"正在使用density函数生成值)。由于density选择密度估计的带宽,因此stat="density"输出比直方图输出平滑得多。减少参数可减少平滑量。

下面的前两个例子是你的情节。第二个使用对各个参数的调整来获得两个大致相似的图,尽管不完全相同,因为核密度估计仍然使输出平滑。这只是为了说明。核密度估计和直方图是两个不同的,与思想相关的东西。

ggplot(df, aes(x = max.diff)) + 
    geom_histogram(stat = "density") + 
    ggtitle("stat='density'; default paramters") 

ggplot(df, aes(x = max.diff)) + 
    geom_histogram(aes(y = ..density..), colour="white") + 
    ggtitle("geom_histogram; default parameters") 

ggplot(df, aes(x = max.diff)) + 
    geom_histogram(stat = "density", n=2^5, adjust=0.1) + 
    ggtitle("stat='density'; n=2^5; Adjust=0.1") 

ggplot(df, aes(x = max.diff)) + 
    geom_histogram(aes(y = ..density..), bins=2^5, colour="white") + 
    ggtitle("geom_histogram; bins=2^5") 

enter image description here

相关问题