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

标签 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)

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

提前致谢,
内特

最佳答案

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

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

更新:
想出了一个更可重复的方法来实现这一点。
sen <- function(..., weights = NULL) {
  mblm::mblm(...)
}

mtcars %>% 
  ggplot(aes(qsec, wt)) +   
  geom_point() +     
  geom_smooth(method = sen)

关于r - 如何将 Theil-Sen 方法与 geom_smooth 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48349858/

相关文章:

r - 转换 data.table 中的*一些*列类

r - 如何在两个级别上躲避pointrange ggplots?

r - ggarrange for 循环和 pdf 中的多页

r - 调整ggplot2中的y轴线位置

r - ggplot/geom_segment : sorting y-axis labels (factors) according to value of variable

r - 根据一列中的值对 R 数据框中的行进行排序

r - 如何检查页面是否在 RSelenium 中完成加载

r - data.table 相当于 dplyr::filter_at

r - 如何修复ggplot连续颜色范围

r - Docker Shiny Server自动进入示例欢迎页面