I'd like to create a stat similar to this example from the ggplot vignette that automatically colors regression lines based on either a positive or negative slope. For example, a regression line with negative slope would appear green, and a positively sloped line would appear red. How can I write that into my stat functions?
What did you tried from the example of the ggplot vignette ?
You should try to modify the function to do what you want.
I think as you want to modify the color that you need to create a new Geom and not a new stat. You could see how it is done for geom_smooth that add by default a blue line for the regression.
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.
This is only half a solution though -- I'd like to be able to feed the geom grouped data, but I can't seem to get it right. For example, using the code above:
x <- 1:20
df <- data.frame(x = c(x,x),
y = c(0.03*x + rnorm(20, sd = 0.1),
-0.03*x + rnorm(20, sd = 0.1)),
group = rep(c("Var1","Var2"),each = 20))
ggplot(df, aes(x = x, y = y)) +
geom_point(aes(color = group)) +
geom_simple_reg()
This produces a single regression line for two distinct groups.