Thanks, @cderv, that put me on the right course. Here's a functioning example of what I'm looking for based on the first sample geom presented at the Extending ggplot2 site.
GeomSimpleReg <- ggproto("GeomSimpleReg", Geom,
required_aes = c("x", "y"),
draw_key = draw_key_point,
draw_panel = function(data, panel_params, coord) {
coords <- coord$transform(data, panel_params)
#fit model and predict
rng <- c(coords$x, na.rm = TRUE)
grid <- data.frame(x = rng)
mod <- lm(y ~ x, data = coords)
grid$y <- predict(mod, newdata = grid)
#get slope of line
slope <- coef(mod)[2]
#set color
if (slope < 0){
def_col <- "purple"
} else {
def_col <- "orange"
}
grid$colour <- def_col
grid::linesGrob(
grid$x, grid$y,
gp = grid::gpar(col = grid$colour)
)
},
default_aes = aes(shape = 19)
)
geom_simple_reg <- function(mapping = NULL, data = NULL, stat = "identity",
position = "identity", na.rm = FALSE, show.legend = NA,
inherit.aes = TRUE, ...) {
layer(
geom = GeomSimpleReg, mapping = mapping, data = data, stat = stat,
position = position, show.legend = show.legend, inherit.aes = inherit.aes,
params = list(na.rm = na.rm, ...)
)
}
#Test positive slope
x <- 1:20
df <- data.frame(x = x,
y = 0.03*x + rnorm(20, sd = 0.1))
ggplot(df, aes(x = x, y = y)) +
geom_point() +
geom_simple_reg()
#test negative slope
df <- data.frame(x = x,
y = -0.03*x + rnorm(20, sd = 0.1))
ggplot(df, aes(x = x, y = y)) +
geom_point() +
geom_simple_reg()