Monday, September 22, 2008

Add boxplots to a scatterplot

par(fig=c(0,0.8,0,0.8), new=TRUE)
plot(mtcars$wt, mtcars$mpg, xlab="Miles Per Gallon",
ylab="Car Weight")
par(fig=c(0,0.8,0.55,1), new=TRUE)
boxplot(mtcars$wt, horizontal=TRUE, axes=FALSE)
par(fig=c(0.65,1,0,0.8),new=TRUE)
boxplot(mtcars$mpg, axes=FALSE)
mtext("Enhanced Scatterplot", side=3, outer=TRUE, line=-3)



To understand this graph, think of the full graph area as going from (0,0) in the lower left corner to (1,1) in the upper right corner. The format of the fig= parameter is a numerical vector of the form c(x1, x2, y1, y2). The first fig= sets up the scatterplot going from 0 to 0.8 on the x axis and 0 to 0.8 on the y axis. The top boxplot goes from 0 to 0.8 on the x axis and 0.55 to 1 on the y axis. I chose 0.55 rather than 0.8 so that the top figure will be pulled closer to the scatter plot. The right hand boxplot goes from 0.65 to 1 on the x axis and 0 to 0.8 on the y axis. Again, I chose a value to pull the right hand boxplot closer to the scatterplot. You have to experiment to get it just right.

fig= starts a new plot, so to add to an existing plot use new=TRUE.

You can use this to combine several plots in any arrangement into one graph.

zz from (Quick R)

=============================================
== my own method:

ll = matrix(c(2, 0, 5, 0, 1, 3, 4, 6, 8, 0, 11, 0, 7, 9, 10, 12), nrow=4, byrow=TRUE)
width = c(0.8, 0.17, 0.8, 0.17)
height = c(0.17, 0.8, 0.17, 0.8)
layout(ll, width, height)

plot.data.list <- list(
cbind(rnorm(200), runif(200)),
cbind(rgeom(200, prob=0.2), runif(200)),
cbind(rgamma(200, shape=2), runif(200)),
cbind(rpois(200, lambda=5), runif(200))
);

for(i in 1:4){
plot.data <- plot.data.list[[i]];
xmax <- max(plot.data[ ,1]);
xmin <- min(plot.data[ ,1]);
ymax <- max(plot.data[ ,2]);
ymin <- min(plot.data[ ,2]);
#scatter plot
par(mar=c(4, 4, 0, 0))
plot(plot.data[ ,1], plot.data[ ,2], pch = 20, ylab = "Y",
xlim = c(xmin, xmax), ylim=c(ymin, ymax), xlab = " ", main="");
#boxplot
par(mar=c(0, 4, 1, 1))
boxplot(plot.data[ ,1], horizontal=TRUE, axes=FALSE, ylim = c(xmin, xmax));
mtext(text=expression("NAMESS"), side = 3, line=-0.5);
par(mar=c(4, 0, 1, 1))
boxplot(plot.data[ ,2], axes=FALSE, ylim=c(ymin, ymax))
}

===================================================