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
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.
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.
stat_smooth: Add a smoother. Aids the eye in seeing patterns in the presence of overplotting.
se. Display confidence interval around smooth? ( TRUE by default, see level to control.)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With