scatterHist <- function(x, y, xlim, ylim, scatterProportion=3, ...) { # Function to draw a scatterplot with marginal histograms # Nigel De Silva # 2006-03-18 # Get call so that can transfer arguments to call .parsXY <-.parsHist <- match.call() # Get histogram info .xhist <- hist(x, plot=FALSE, ...) .yhist <- hist(y, plot=FALSE, ...) # Determine limits of plot if( missing(xlim) ) xlim <- range(.xhist$breaks) if( missing(ylim) ) ylim <- range(.yhist$breaks) .top <- max(c(.xhist$counts, .yhist$counts)) # Set up graphical device def.par <- par(no.readonly = TRUE) # save current, for resetting nf <- layout(matrix(c(2,0,1,3),2,2,byrow=TRUE), c(scatterProportion,1), c(1,scatterProportion), TRUE) # layout.show(nf) # Plot graphs # Graph 1: Scatter plot par(mar=c(5,5,1,1)) .parsXY$main <- NULL .parsXY$scatterProportion <- NULL .parsXY[[1]] <- as.name("plot") eval(.parsXY, sys.frame(sys.parent())) # Graph 2: X Histogram par(mar=c(0,5,4,1)) .parsHist$x <- .parsHist$y <- .parsHist$xlab <- .parsHist$ylab <- NULL .parsHist$scatterProportion <- NULL .parsHist[[1]] <- as.name("barplot") .parsHist$height <- .xhist$counts .parsHist$axes <- FALSE .parsHist$ylim <- c(0, .top) .parsHist$space <- 0 eval(.parsHist, sys.frame(sys.parent())) # Graph 2: Y Histogram par(mar=c(5,0,1,4)) .parsHist$main <- NULL .parsHist$ylim <- NULL .parsHist$height <- .yhist$counts .parsHist$xlim <- c(0, .top) .parsHist$horiz <- TRUE eval(.parsHist, sys.frame(sys.parent())) #Reset graphical parameters par(def.par) } x <- pmin(3, pmax(-3, rnorm(1000))) y <- pmin(3, pmax(-3, rnorm(1000))) scatterHist(x,y, xlab="X", main="Scatterplot with Marginal Histograms", scatterProportion=4)