Last active
April 7, 2017 01:12
-
-
Save rBatt/fd3e3b91efdad06c73cc04d2f124f911 to your computer and use it in GitHub Desktop.
Scatter Plot with per-subset regression lines
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#' Scatter plot with certain groups of points getting own regression and fitted line | |
#' | |
#' @param Data a data.table | |
#' @param x,y,lineBy character, name of column in \code{Data} | |
#' @param ptCol,lineCol character or quoted expression (call) for point or line color, repsectively | |
#' @param ... arguments to be passed to \code{\link{plot}} and \code{link{lines}} | |
#' | |
#' @examples | |
#' dt <- data.table( | |
#' x=x<-rnorm(9, sd=2), # why <- is better than = | |
#' dog=x*2+rnorm(9), | |
#' goat=x*-1+rnorm(9, mean=6) | |
#' ) | |
#' dt <- melt(dt, id.vars='x', measured.vars=c('dog','goat'), variable.name='animal') | |
#' q_ptCol <- bquote(c('dog'='blue','goat'='red')[animal]) | |
#' scatterLine(dt, x='x', y='value', lineBy='animal', ptCol=q_ptCol, lineCol='lightblue') | |
#' | |
#' @export | |
scatterLine <- function(Data, x, y, lineBy, ptCol='black', pch=16, lineCol='black', ...){ | |
dots <- list(...) | |
if(is.null(dots$ylab)){ | |
dots <- modifyList(dots, list(ylab=y)) | |
} | |
if(is.null(dots$xlab)){ | |
dots <- modifyList(dots, list(xlab=x)) | |
} | |
xval <- x # messes up in order(get(x)) otherwise ... weird | |
yval <- y | |
Data[,do.call(plot, args=c(list(get(xval), get(yval), col=eval(ptCol), pch=pch),dots))] | |
Data[,j={ | |
ulb <- unique(get(lineBy)) | |
nlb <- length(ulb) | |
for(r in 1:nlb){ # loop through each region | |
.SD[get(lineBy)==ulb[r]][order(get(xval)),j={ # subset to r-th region, order points so x is increasing (so that predicted line plots correctly) | |
xval <- get(xval) | |
yval <- get(yval) | |
lines(xval, predict(lm(yval~xval)), col=eval(lineCol), ...) | |
}] | |
} | |
}] | |
invisible(NULL) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The example: