ggplot 黄土线从一个数据集到另一个散点图

ggplot loess line from one dataset over scatterplot of another

下面的函数计算分箱平均值,相对于每个分箱中观察值的数量调整图表上分箱点的大小,并绘制一条穿过分箱均值的低线。然而,我不想通过 bin 方法绘制最低线,而是想通过原始数据集绘制线,以便 lowess 线上的误差带代表实际数据集中的不确定性,而不是分箱平均值中的不确定性。如何修改 geom_smooth() 以便它使用 df 而不是 dfplot 绘制线条?

library(fields)
library(ggplot2)

binplot <- function(df, yvar, xvar, sub = FALSE, N = 50, size = 40, xlabel = "X", ylabel = "Y"){
  if(sub != FALSE){
    df <- subset(df, eval(parse(text = sub)))

  }

  out <- stats.bin(df[,xvar], df[,yvar], N= N)
  x <- out$centers
  y <- out$stats[ c("mean"),]
  n <-  out$stats[ c("N"),] 
  dfplot <- as.data.frame(cbind(x,y,n))

  if(size != FALSE){
    sizes <- n * (size/max(n))

  }else{
    sizes = 3
  }

    ggplot(dfplot, aes(x,y)) +
      xlab(xlabel) +
      ylab(ylabel) +
      geom_point(shape=1, size = sizes) +
      geom_smooth() 
}

这是一个可重现的示例,演示了该函数当前的工作原理:

sampleSize <- 10000
x1 <- rnorm(n=sampleSize, mean = 0, sd = 4)
y1 <-  x1 * 2 + x1^2 * .3 +  rnorm(n=sampleSize, mean = 5, sd = 10)
binplot(data.frame(x1,y1), "y1", "x1", N = 25)

如您所见,如果每个 bin 具有相同数量的观测值,则最低线上的误差带反映了不确定性,但它们没有。极端的 bins 的观测值要少得多(如点的大小所示),最低线的误差带应该反映出这一点。

您可以为每一层显式设置 data= 参数。您还需要更改美学映射,因为原始 data.frame 具有不同的列名。只需将您的 geom_smooth 呼叫更改为

geom_smooth(data=df, aes_string(xvar, yvar)) 

使用样本数据,返回