This is a question that relates to my earlier question geom_smooth with facet_grid and different fitting functions. In that question, I was trying to use a different fitting
Here's the solution, which greatly benefited from this post. I don't know why the previous version didn't work, but this seems to work fine.
# Load library
library(ggplot2)
# Load data
data(mtcars)
# Smoothing function with different behaviour depending on the panel
custom.smooth <- function(formula, data,...){
smooth.call <- match.call()
if(as.numeric(unique(data$PANEL)) == 6) {
# Nonlinear regression
smooth.call[[1]] <- quote(nls)
# Specify formula
smooth.call$formula <- as.formula("y ~ a * x ^ b")
# Add initial parameters
smooth.call$start <- c(a = 300, b = -0.5)
}else{
# Linear regression
smooth.call[[1]] <- quote(lm)
}
# Perform fit
eval.parent(smooth.call)
}
# Plot data with custom fitting function
p <- ggplot(mtcars,aes(x = disp, y = mpg)) + geom_point() + facet_grid(gear ~ am)
p <- p + geom_smooth(method = "custom.smooth", se = FALSE)
print(p)