draw_boxplot_structure <- function(
q0, q1, q2, q3, q4,
gaps = c(.3, .2, .3),
margins_lo = c(.05, .05, .05, .05),
margins_hi = c(.05, .05, .05, .05))
{
# This function was first written by Copilot Basic.
# I then edited it.
s1 <- gaps[1] * min(q1 - q0, q2 - q1)
s2 <- gaps[2] * min(q2 - q1, q3 - q2)
s3 <- gaps[3] * min(q3 - q2, q4 - q3)
plot(
0, 0,
type = "n",
xlim = c(0, 10),
ylim = c(q0 - .1 * (q4 - q0),
q4 + .1 * (q4 - q0)),
xaxt = "n",
yaxt = "n",
xlab = "",
ylab = ""
)
abline(h = q0, lty = 3, col = "lightgrey")
abline(h = q1, lty = 3, col = "lightgrey")
abline(h = q2, lty = 3, col = "lightgrey")
abline(h = q3, lty = 3, col = "lightgrey")
abline(h = q4, lty = 3, col = "lightgrey")
axis(2)
cols <- c(
"#008cba",
"#008cba",
"#008cba",
"#008cba"
)
# ---------- BOXPLOT ----------
xbox <- 7.5
bw <- 0.8
rect(
xbox - bw/2, q1,
xbox + bw/2, q3,
col = "white",
border = "black",
lwd = 2
)
segments(xbox, q0, xbox, q1, lwd = 2)
segments(xbox, q3, xbox, q4, lwd = 2)
segments(xbox - bw/4, q0,
xbox + bw/4, q0, lwd = 2)
segments(xbox - bw/4, q4,
xbox + bw/4, q4, lwd = 2)
segments(
xbox - bw/2, q2,
xbox + bw/2, q2,
lwd = 3
)
text(
rep(xbox + 0.9, 5),
c(q0, q1, q2, q3, q4),
labels = c("q0", "q1", "q2", "q3", "q4"),
pos = 4
)
# ---------- CONSTRUCTION DIAGRAM ----------
xc <- 3
segments(xc, q0, xc, q4, lwd = 1)
segs <- list(
c(q0, q1 - s1),
c(q1 + s1, q2 - s2),
c(q2 + s2, q3 - s3),
c(q3 + s3, q4)
)
for(i in 1:4){
lo <- segs[[i]][1]
hi <- segs[[i]][2]
rect(
xc - 0.5, lo,
xc + 0.5, hi,
col = cols[i],
border = NA
)
rng <- hi - lo
ml <- lo + margins_lo[i] * rng
mh <- hi - margins_hi[i] * rng
rect(
xc - 0.5, lo,
xc + 0.5, ml,
col = "#ffa500",
border = NA
)
rect(
xc - 0.5, mh,
xc + 0.5, hi,
col = "#ffa500",
border = NA
)
text(
xc - 1.5,
(lo + hi)/2,
paste("segment", i),
cex = .8
)
}
# ---------- GAP BRACKETS ----------
draw_gap <- function(y1, y2, x = 4.2, lab){
arrows(
x, y1,
x, y2,
code = 3,
angle = 90,
length = .08,
col = "darkred",
lwd = 2
)
text(
x + 0.8,
mean(c(y1, y2)),
lab,
col = "darkred"
)
}
draw_gap(q1 - s1, q1 + s1, lab = "gap[1]")
draw_gap(q2 - s2, q2 + s2, lab = "gap[2]")
draw_gap(q3 - s3, q3 + s3, lab = "gap[3]")
# ---------- HINGE / MEDIAN LABELS ----------
points(
rep(xc, 8),
c(q1 - s1, q1 + s1,
q2 - s2, q2 + s2,
q3 - s3, q3 + s3,
q0, q4),
pch = 19
)
mtext(
"Construction of data generated by boxplot_data()",
side = 3,
line = 0.5
)
legend(
"bottomleft",
inset=c(0,-0.2),
xpd = TRUE,
fill = c(cols[1], "#ffa500"),
legend = c(
"fill these regions with additional data (distribution controlled by shapes)",
"no further data in these regions (excluded by margins)"
),
bty = "n"
)
}
par(las = 1)
draw_boxplot_structure(
q0 = 0,
q1 = 10,
q2 = 20,
q3 = 35,
q4 = 50,
gaps = c(.1, .6, .2),
margins_lo = c(.3, .5, 0, 0),
margins_hi = c(0, 0, 0, .8)
)