# Generate some data library(MASS) set.seed(101) n <- 50000 X <- mvrnorm(n, mu=c(.5,2.5), Sigma=matrix(c(1,.6,.6,1), ncol=2)) # A color palette from blue to yellow to red library(RColorBrewer) k <- 11 my.cols <- rev(brewer.pal(k, "RdYlBu")) ## compute 2D kernel density, see MASS book, pp. 130-131 z <- kde2d(X[,1], X[,2], n=50) # Make the base plot plot(X, xlab="X label", ylab="Y label", pch=19, cex=.4) # Draw the colored contour lines contour(z, drawlabels=FALSE, nlevels=k, col=my.cols, add=TRUE, lwd=2) # Add lines for the mean of X and Y abline(h=mean(X[,2]), v=mean(X[,1]), col="gray", lwd=1.5) # Add the correlation coefficient to the top left corner legend("topleft", paste("R=", round(cor(X)[1,2],3)), bty="n") ## Other methods to fix overplotting # Make points smaller - use a single pixel as the plotting charachter plot(X, pch=".") # Hexbinning library(hexbin) plot(hexbin(X[,1], X[,2])) # Make points semi-transparent library(ggplot2) qplot(X[,1], X[,2], alpha=I(.1)) # The smoothScatter function (graphics package) smoothScatter(X)