|
| 1 | +#Produce a histogram for each variable in a dataset. |
| 2 | +all.hist <- function(x){ |
| 3 | + sapply(colnames(x), function(i)hist(x[,i], main = i, |
| 4 | + xlab="Value", col="lightblue")) |
| 5 | +} |
| 6 | + |
| 7 | +#Produce a kernel density plot w/normal curve for each |
| 8 | +#variable in a dataset. |
| 9 | +all.density.plot <- function(x){ |
| 10 | + sapply(colnames(x), function(i)plot(density(x[,i]), |
| 11 | + main = i, xlab="Value", col="red", lwd=2)) |
| 12 | +} |
| 13 | + |
| 14 | +#Produce a scatterplot matrix with histograms |
| 15 | +#on the diagonal and correlation statistics in the |
| 16 | +#upper panel using the base function pairs() |
| 17 | +#http://handlesman.blogspot.com/2011/03/matrix-plot-with-confidence-intervals.html |
| 18 | + |
| 19 | +## put histograms on the diagonal |
| 20 | +panel.hist <- function(x, ...) |
| 21 | +{ |
| 22 | + usr <- par("usr"); on.exit(par(usr)) |
| 23 | + par(usr = c(usr[1:2], 0, 1.5) ) |
| 24 | + h <- hist(x, plot = FALSE) |
| 25 | + breaks <- h$breaks; nB <- length(breaks) |
| 26 | + y <- h$counts; y <- y/max(y) |
| 27 | +rect(breaks[-nB], 0, breaks[-1], y, col="lavender", ...) |
| 28 | +} |
| 29 | + |
| 30 | +## put correlations & 95% CIs on the upper panels, |
| 31 | +panel.cor <- function(x, y, digits=2, prefix="", cex.cor, ...) |
| 32 | +{ |
| 33 | + usr <- par("usr"); on.exit(par(usr)) |
| 34 | + par(usr = c(0, 1, 0, 1)) |
| 35 | + r <- cor(x, y,use="complete.obs") |
| 36 | + txt <- format(c(r, 0.123456789), digits=digits)[1] |
| 37 | + prefix <- "r = " |
| 38 | + rc <- cor.test(x,y) |
| 39 | + rci <- rc$conf.int |
| 40 | + txt2 <- format(c(rci, 0.123456789), digits=digits)[1] |
| 41 | + txt3 <- format(c(rci, 0.123456789), digits=digits)[2] |
| 42 | + prefix2 <- "\nCI = " |
| 43 | + txt <- paste(prefix, txt, prefix2, txt2, ", ", txt3, sep="") |
| 44 | + if(missing(cex.cor)) cex.cor <- 0.8/strwidth(txt) |
| 45 | + text(0.5, 0.5, txt, cex = 1) |
| 46 | +} |
| 47 | + |
| 48 | +#Combine helper functions |
| 49 | +pairs(iris[1:4], lower.panel=panel.smooth, cex = .8, pch = 21, bg="steelblue", |
| 50 | + diag.panel=panel.hist, cex.labels = 1.2, font.labels=2, upper.panel=panel.cor) |
| 51 | + |
0 commit comments