Skip to content
Prev 383157 / 398502 Next

ggplot stat smooth and poly

On Thu, Apr 2, 2020 at 6:10 PM PIKAL Petr <petr.pikal at precheza.cz> wrote:

            
Looks like there's a tryCatch around each panel, but not for each group
within panel. So this would work:

p + geom_point(size=2) + facet_wrap(~three) +
    stat_smooth(method="lm", formula=y~poly(x,2))

but one problematic group is enough to make a whole panel fail.

Other than rewriting StatSmooth$compute_panel to protect each per-group
call, a workaround could be to replace method="lm" by a safe wrapper, e.g.,:

plm <- function(formula, data, ...)
{
    ocall <- match.call(expand.dots = TRUE)
    ocall[[1]] <- quote(lm)
    fm <- try(eval(ocall, parent.frame()), silent = TRUE)
    if (inherits(fm, "try-error"))
    {
        ocall[[2]] <- y ~ x
        fm <- eval(ocall, parent.frame())
    }
    fm
}

p + geom_point(size=2) + stat_smooth(method=plm, formula=y~poly(x,2))

-Deepayan

Best regards