Skip to content

Instantly share code, notes, and snippets.

@rBatt
Last active April 7, 2017 01:12
Show Gist options
  • Save rBatt/fd3e3b91efdad06c73cc04d2f124f911 to your computer and use it in GitHub Desktop.
Save rBatt/fd3e3b91efdad06c73cc04d2f124f911 to your computer and use it in GitHub Desktop.
Scatter Plot with per-subset regression lines
#' 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)
}
@rBatt
Copy link
Author

rBatt commented Apr 7, 2017

The example:

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')

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