library(plyr)
n <- 101
s <- seq(-5, 5, length.out = n)
# one dimensional case
df <- data.frame(x = s)
df <- mutate(df, y = -x^2 + 2*x - 3 + rnorm(n, 0, 2))
with(df, plot(x, y))
mod <- lm(y ~ x + I(x^2), data = df)
(p <- as.mpoly(mod))
f <- as.function(p)
lines(s, f(s), col = "red")
# one dimensional case with ggplot2
library(ggplot2); theme_set(theme_bw())
qplot(x, y, data = df)
qplot(x, y, data = df) +
stat_function(fun = f, colour = "red")
# two dimensional case with ggplot2
df <- expand.grid(x = s, y = s)
df <- mutate(df, z = x^2 - y^2 + 2 * x*y + rnorm(n^2, 0, 3))
qplot(x, y, data = df, geom = "raster", fill = z)
mod <- lm(z ~ x + y + I(x^2) + I(y^2) + I(x*y), data = df)
p <- as.mpoly(mod)
f <- as.function(p)
df$fit <- apply(df[,c("x","y")], 1, f)
qplot(x, y, data = df, geom = "raster", fill = fit)
qplot(x, y, data = df, geom = "raster", fill = z - fit) # residuals