r - 了解 ggplot2 中的带宽平滑

标签 r ggplot2

真实数据 = https://www.dropbox.com/s/pc5tp2lfhafgaiy/realdata.txt

模拟 = https://www.dropbox.com/s/5ep95808xg7bon3/simulation.txt

使用带宽 = 1.5 的此数据的密度图为我提供了以下图:

prealdata = scan("realdata.txt")
simulation = scan("simulation.txt")
plot(density(log10(realdata), bw=1.5))
lines(density(log10(simulation), bw=1.5), lty=2)

enter image description here

但是使用 ggplot2 绘制相同的数据,带宽参数(调整)的工作方式似乎有所不同。为什么?
vec1 = data.frame(x=log10(realdata))
vec2 = data.frame(x=log10(simulation))
require(ggplot2)
ggplot() +
geom_density(aes(x=x, linetype="real data"), data=vec1, adjust=1.5) +
geom_density(aes(x=x, linetype="simulation"), data=vec2, adjust=1.5) +
scale_linetype_manual(name="data", values=c("real data"="solid", "simulation"="dashed"))

enter image description here

也非常欢迎有关如何更好地平滑这些数据的建议!

最佳答案

adjust=bw= 不一样.当你绘图时

plot(density(log10(realdata), bw=1.5))
lines(density(log10(simulation), bw=1.5), lty=2)

你得到与 ggplot 相同的东西

enter image description here

无论出于何种原因,ggplot不允许您指定 bw=范围。默认情况下,density用途 bw.nrd0()因此,当您使用基本图形为绘图更改此值时,您不能使用 ggplot 更改此值。 .但是get使用的是adjust*bw .所以既然我们知道如何计算默认值 bw ,我们可以重新计算adjust=给 use 相同的值。
#helper function
bw<-function(b, x) { b/bw.nrd0(x) }

require(ggplot2)
ggplot() +
geom_density(aes(x=x, linetype="real data"), data=vec1, adjust=bw(1.5, vec1$x)) +
geom_density(aes(x=x, linetype="simulation"), data=vec2, adjust=bw(1.5, vec2$x)) +
scale_linetype_manual(name="data", 
    values=c("real data"="solid", "simulation"="dashed"))

这导致

enter image description here

这与基本图形图相同。

关于r - 了解 ggplot2 中的带宽平滑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24985361/

相关文章:

r - 将年份标签放置在轴上的年初

R包DARCH深度信念神经网络似乎无法学习 'exclusive or'

r - ggplot 中十分位数的低、中高颜色

R删除条目不是日期的行

r - 如何以智能方式将互联网上的图像插入到 R bookdown 生成的 pdf 文件中?

r - 绘制GLM回归方程并在GGPlot上平方R

r - 如何使用不同的 y 轴文本长度获得相同的面板宽度

r - 在scale_shape_manual中分配40个或更多形状

r - 使用逆采样从分布函数生成随机变量

r - 如何向构面标签添加上标