Understanding bandwidth smoothing in ggplot2

后端 未结 1 884
臣服心动
臣服心动 2020-12-19 12:20

realdata = https://www.dropbox.com/s/pc5tp2lfhafgaiy/realdata.txt

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

A density plot of thi

相关标签:
1条回答
  • 2020-12-19 13:11

    adjust= is not the same as bw=. When you plot

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

    you get the same thing as ggplot

    enter image description here

    For whatever reason, ggplot does not allow you to specify a bw= parameter. By default, density uses bw.nrd0() so while you changed this for the plot using base graphics, you cannot change this value using ggplot. But what get's used is adjust*bw. So since we know how to calculate the default bw, we can recalculate adjust= to give use the same value.

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

    And that results in

    enter image description here

    which is the same as the base graphics plot.

    0 讨论(0)
提交回复
热议问题