Skip to content

Instantly share code, notes, and snippets.

@k-barton
Last active November 20, 2020 11:04
Show Gist options
  • Save k-barton/7fe12905f3af0773656848cbf2070adc to your computer and use it in GitHub Desktop.
Save k-barton/7fe12905f3af0773656848cbf2070adc to your computer and use it in GitHub Desktop.
A low-level, customizable box- or dot-whiskers plot, using base graphics.
bwplot <-
function(x, y, lower, upper, box.lower, box.upper, w = .25, boxw = 0.8,
names = NULL, xlab = NULL, ylab = NULL, main = NULL,
lty = par("lty"), lty.stap = lty, lty.vert = lty, lty.box = lty,
lwd = par("lwd"),
border = par("fg"),
col.box = "white", col.pt = par("fg"),
xlim, ylim, add = FALSE, ann = !add, axes = TRUE,
pch = par("pch"), cex = par("cex"), bg = par("bg")) {
if(!isTRUE(add)) {
plot.new()
if(missing(xlim))
xlim <- extendrange(x) + (max(1, boxw) * c(-w, w))
if(missing(ylim)) ylim <- range(c(lower, upper))
plot.window(xlim, ylim)
if(axes) {
axis(1, at = x, labels = names, tick = 0, line = -.33)
axis(2)
box()
}
title(main, xlab = xlab, ylab = ylab)
}
segments(x - w, upper, x + w, upper, lty = lty.stap, col = border, lwd = lwd)
segments(x - w, lower, x + w, lower, lty = lty.stap, col = border, lwd = lwd)
if(!missing(box.lower) && !missing(box.upper)) {
w1 <- w * boxw
rect(x - w1, box.lower, x + w1, box.upper, border = border, lwd = lwd, lty = lty.box,
col = col.box)
segments(x, upper, x, box.upper, lty = lty.vert, lwd = lwd, col = border)
segments(x, lower, x, box.lower, lty = lty.vert, lwd = lwd, col = border)
} else {
segments(x, upper, x, lower, lty = lty.vert, lwd = lwd, col = border)
}
points(x, y, pch = pch, cex = cex, bg = bg, col = col.pt)
}
@k-barton
Copy link
Author

k-barton commented Oct 1, 2020

Examples:

bwplot(x = c(1, 2, 4, 5), y = c(2,1,3,5),
       lower = c(1,0,1,1), upper = c(3,4,5,6),
       pch = 19, names = LETTERS[1:4])

obraz

f <- gl(3, 25)
x <- rnorm(length(f), mean = c(-1, 1.23, 0)[f]) 

stats <- do.call("rbind", tapply(x, f, quantile, simplify = TRUE)) 

bwplot(y = stats[, "50%"],
       lower = stats[, "0%"],
       upper = stats[, "100%"],
       box.lower = stats[, "25%"],
       box.upper = stats[, "75%"],
       names = paste("group", 1:3),
       boxw = .25, pch = 22,
       bg = 1:3,
       col.box = rainbow(3, v = .9, s = .1)
       )

obraz

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment