Transforming LOESS smooths

65 views
Skip to first unread message

Gad Abraham

unread,
Aug 29, 2011, 8:29:16 PM8/29/11
to ggplot2
Hi,

I'm plotting a LOESS smooth of proportions. To ensure strict
positivity of the estimates, I've transformed the proportions to log-
odds scale (logit), and smoothed that instead.

Now, I'd like to plot these smooths on the original proportion scale,
1/(1+exp(-y_smooth)), how can that be done?

Thanks,
Gad


# an artificial example
library(ggplot2)

x <- seq(4, 5, length=30)
y <- plogis(x + rnorm(length(x)))
d <- data.frame(x=c(1, 2, 3, x), y=c(0.01, 0.02, 0.03, y))

# proportions scale
g <- ggplot(d, aes(x, y)) + geom_point()
g <- g + stat_smooth(method="loess")
g

# logit scale
d$y2 <- log(d$y / (1 - d$y))
g2 <- ggplot(d, aes(x, y2)) + geom_point()
g2 <- g2 + stat_smooth(method="loess")
g2

Gad Abraham

unread,
Sep 2, 2011, 12:20:43 AM9/2/11
to ggplot2
I managed to hack a solution based on
http://stackoverflow.com/questions/2370648/modify-lm-or-loess-function-to-use-it-within-ggplot2s-geom-smooth
:

logit <- function(p) log(p / (1 - p))
invlogit <- function(p) 1 / (1 + exp(-p))

loess2 <- function(...)
{
m <- match.call()
m[[1]] <- quote(loess)
m[[2]] <- quote(logit(y) ~ x)
l <- eval.parent(m)
class(l) <- "loess2"
l
}

predict.loess2 <- function(object, ...)
{
class(object) <- "loess"
p <- stats::predict(object, ...)
if(is.list(p)) {
y <- invlogit(p$fit)
ymin <- invlogit(p$fit - 2 * p$se.fit)
ymax <- invlogit(p$fit + 2 * p$se.fit)
p$fit <- cbind(y, ymin, ymax)
p
} else {
invlogit(p)
}
}

g <- ggplot(d, aes(x, y)) + geom_point()
g <- g + stat_smooth(method="loess2")
g

Hadley Wickham

unread,
Sep 12, 2011, 10:34:02 AM9/12/11
to Gad Abraham, ggplot2
This is a fine solution, but generally for any complex models you're
best off doing the fitting and prediction outside of ggplot2 and then
plotting the results.

Hadley

> --
> You received this message because you are subscribed to the ggplot2 mailing list.
> Please provide a reproducible example: http://gist.github.com/270442
>
> To post: email ggp...@googlegroups.com
> To unsubscribe: email ggplot2+u...@googlegroups.com
> More options: http://groups.google.com/group/ggplot2
>

--
Assistant Professor / Dobelman Family Junior Chair
Department of Statistics / Rice University
http://had.co.nz/

Reply all
Reply to author
Forward
0 new messages