[R] Combined plot: Scatter + density plot

Ralf B ralf.bierig at gmail.com
Tue Sep 21 07:34:34 CEST 2010


Hi,

in order to save space for a publication, it would be nice to have a
combined scatter and density plot similar to what is shows on

http://addictedtor.free.fr/graphiques/RGraphGallery.php?graph=78

I wonder if anybody perhaps has already developed code for this and is
willing to share. This is the reproducible code for the histogram
version obtained from the site:

def.par <- par(no.readonly = TRUE) # save default, for resetting...
x <- pmin(3, pmax(-3, rnorm(50)))
y <- pmin(3, pmax(-3, rnorm(50)))
xhist <- hist(x, breaks=seq(-3,3,0.5), plot=FALSE)
yhist <- hist(y, breaks=seq(-3,3,0.5), plot=FALSE)
top <- max(c(xhist$counts, yhist$counts))
xrange <- c(-3,3)
yrange <- c(-3,3)
nf <- layout(matrix(c(2,0,1,3),2,2,byrow=TRUE), c(3,1), c(1,3), TRUE)
par(mar=c(3,3,1,1))
plot(x, y, xlim=xrange, ylim=yrange, xlab="", ylab="")
par(mar=c(0,3,1,1))
barplot(xhist$counts, axes=FALSE, ylim=c(0, top), space=0)
par(mar=c(3,0,1,1))
barplot(yhist$counts, axes=FALSE, xlim=c(0, top), space=0, horiz=TRUE)

par(def.par)

I am basically stuck from line 6 where the bin information from the
histogram is used for determining plotting sizes. Density are
different and don't have (equal) bins and their size would need to be
determined differently. I wonder if somebody here has created such a
diagram already and is willing to share ideas/code/pointers to similar
examples. Your effort is highly appreciated.

Thanks a lot,
Ralf



More information about the R-help mailing list