Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use Theil-Sen method with geom_smooth

Tags:

r

ggplot2

I am trying to implement a theil-sen operator in ggplot's geom_smooth. In an ideal world it would read something like: geom_smooth(..., methods= "mblm"). I cannot seem to find an answer to this, nor can I figure out how I would customize the methods for this. Any advice, pointers, or code help would be greatly appreciated.

I would like to effectively replacing add "mblm" to the methods options in 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)

Neither works. I generate the warning Warning message: Computation failed in stat_smooth(): unused argument (weights = weight), which is essential an error in the geom_smooth line. Any help would be appreciated.

Thanks in advance, Nate

like image 671
nate-m Avatar asked Jan 19 '18 21:01

nate-m


People also ask

What is the use of Geom_smooth?

You can use the geom_smooth layer to look for patterns in your data. We use this layer to Plot two continuous position variables in the graph. The basic setting for described geometry is shown in the following plot.

What does Geom_smooth () using formula YX mean?

The warning geom_smooth() using formula 'y ~ x' is not an error. Since you did not supply a formula for the fit, geom_smooth assumed y ~ x, which is just a linear relationship between x and y.

What does Stat_smooth method lm do?

stat_smooth: Add a smoother. Aids the eye in seeing patterns in the presence of overplotting.

What does SE stand for in Geom_smooth?

se. Display confidence interval around smooth? ( TRUE by default, see level to control.)


1 Answers

I figured it out. Here is the answer for completion.

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

Update: Figured out a more repeatable way to accomplish this.

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

mtcars %>% 
  ggplot(aes(qsec, wt)) +   
  geom_point() +     
  geom_smooth(method = sen)
like image 83
nate-m Avatar answered Oct 02 '22 20:10

nate-m