【问题标题】:Understanding bandwidth smoothing in ggplot2了解 ggplot2 中的带宽平滑
【发布时间】:2026-01-02 13:10:02
【问题描述】:

真实数据 = 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)

但是使用 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"))

也非常欢迎就如何更好地平滑这些数据提出建议!

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    adjust=bw= 不同。当你绘图时

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

    你得到和ggplot一样的东西

    无论出于何种原因,ggplot 不允许您指定 bw= 参数。默认情况下,density 使用 bw.nrd0(),因此当您使用基本图形更改绘图时,您无法使用 ggplot 更改此值。但是得到的是adjust*bw。因此,既然我们知道如何计算默认的bw,我们可以重新计算adjust= 以使用相同的值。

    #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"))
    

    结果是

    与基本图形绘图相同。

    【讨论】:

    • 只是一个更新,bw 现在在 geom_density 的参数列表中。