如何将 Theil-Sen 方法与 geom_smooth 一起使用

nat*_*e-m 5 r ggplot2

我正在尝试在 ggplot 的 geom_smooth 中实现 theil-sen 运算符。在一个理想的世界,将读取类似:geom_smooth(..., methods= "mblm")。我似乎无法找到答案,也无法弄清楚如何为此自定义方法。任何建议、指针或代码帮助将不胜感激。

我想有效地将​​ add "mblm" 替换为 geom_smooth 中的方法选项:

library(tidyverse)
library(mblm)


# Option 1 - adding 'mblm' into the methods directly
ggplot(mtcars, aes(qsec, wt))+   
geom_point() +     
geom_smooth(method='mblm')

# Option 2 - defining the Theil-Sen function outside
ts_fit <- mblm(qsec ~ wt, data = mtcars)
ggplot(mtcars, aes(qsec, wt))+   
geom_point() +     
geom_smooth( alpha=0,method=ts_fit)
Run Code Online (Sandbox Code Playgroud)

两者都不起作用。我生成了警告Warning message: Computation failed in stat_smooth(): unused argument (weights = weight),这是 geom_smooth 行中必不可少的错误。任何帮助,将不胜感激。

提前致谢,内特

nat*_*e-m 10

我想到了。这是完成的答案。

# Option 2 - defining the Theil-Sen function outside
ts_fit <- mblm(qsec ~ wt, data = mtcars)

ggplot(mtcars, aes(qsec, wt))+   
geom_point() +     
  geom_abline(intercept = coef(ts_fit)[1], slope = coef(ts_fit)[2])
Run Code Online (Sandbox Code Playgroud)

更新:想出了一种更可重复的方法来实现这一点。

sen <- function(..., weights = NULL) {
  mblm::mblm(...)
}

mtcars %>% 
  ggplot(aes(qsec, wt)) +   
  geom_point() +     
  geom_smooth(method = sen)
Run Code Online (Sandbox Code Playgroud)