Skip to content

Instantly share code, notes, and snippets.

@bbolker
Created November 16, 2022 02:04
Show Gist options
  • Select an option

  • Save bbolker/d23ee718846cc30ab852860f5d3b6e38 to your computer and use it in GitHub Desktop.

Select an option

Save bbolker/d23ee718846cc30ab852860f5d3b6e38 to your computer and use it in GitHub Desktop.
comparing boxplot hinge calculation between base R and ggplot
## hinges as computed by stat_boxplot
my_hinges <- function(y, type = 7, coef = 1.5) {
qs <- as.numeric(stats::quantile(y, c(0.25, 0.75), type = type))
iqr <- diff(qs)
outliers <- y < qs[1]-coef*iqr | y > qs[2] + coef*iqr
hinges <- range(c(qs, y[!outliers]))
return(hinges)
}
f_hinges <- function(x) {
## guts of stats::fivenum, without NA removal etc etc
x <- sort(x)
n <- length(x)
n4 <- floor((n + 3)/2)/2
d <- c(1, n4, (n + 1)/2, n + 1 - n4, n)
res <- 0.5 * (x[floor(d)] + x[ceiling(d)])
res[c(2,4)]
}
set.seed(101)
x <- sample(1:6, size = 4, replace = TRUE)
my_hinges(x)
f_hinges(x)
## compare boxplots
boxplot(x)
library(ggplot2)
ggplot() + geom_boxplot(aes(y = x))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment