Skip to content

Instantly share code, notes, and snippets.

@shenqi
Last active August 29, 2015 14:01
Show Gist options
  • Save shenqi/29b42a6be83ec9e0517d to your computer and use it in GitHub Desktop.
Save shenqi/29b42a6be83ec9e0517d to your computer and use it in GitHub Desktop.
Extension of ggplot2 to work friendly with lm object
library(ggplot2)
require(ggplot2)
# usage
#
# stat_r2(lm_obj, x, y, adjusted = FALSE, digits=NULL, ...)
# lm_obj lm object given by lm()
# x, y positional coordinate of r2 value
# adjusted use adjusted R2 instead
# digits see format()
# ... other arguments passed to geom_text()
#
# geom_lm_line(lm_obj, x = NULL, ...)
# lm_obj lm object given by lm()
# x string indicating which variable to draw; default NULL to use first independent variable
# ... other arguments passed to geom_abline()
stat_r2 <- function(lm_obj, x, y, adjusted = FALSE, digits=NULL, ...){
stopifnot(is.numeric(x), is.numeric(y))
value <- ifelse(adjusted, summary(lm_obj)$adj.r.squared, summary(lm_obj)$r.squared)
stopifnot(is.numeric(value))
r2 <- as.character(as.expression(paste0(ifelse(adjusted,
'plain(Adjusted)~{R^2} == ', 'R^2 == '),
as.character(format(value, digits=digits)))))
dd <- data.frame(x=x, y=y, r2=r2)
return(geom_text(data=dd, mapping=aes(x=x, y=y, label=r2, shape=NULL), parse=T, ...))
}
geom_lm_line <- function(lm_obj, x=NULL, ...){
co <- lm_obj$coefficients
stopifnot(is.numeric(co[[1]]))
return(geom_abline(intercept=co[[1]], slope=ifelse(is.null(x), co[[2]], co[[x]]), ...))
}
@ronrest
Copy link

ronrest commented May 14, 2015

geom_lm_line() is very handy

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment