Skip to content

Instantly share code, notes, and snippets.

@tgs
Created May 26, 2015 22:20
Show Gist options
  • Save tgs/7aca6b70719bc5e2e796 to your computer and use it in GitHub Desktop.
Save tgs/7aca6b70719bc5e2e796 to your computer and use it in GitHub Desktop.
Add median to ggplot2 histogram
library(proto)
library(ggplot2)
stat_hist_summary <- function (mapping = NULL, data = NULL, geom = "vline", position = "identity",
fun = median, ...) {
StatHistSummary$new(mapping = mapping, data = data, geom = geom,
position = position, fun = fun, ...)
}
StatHistSummary <- proto(ggplot2:::Stat, {
objname <- "hist_summary"
default_geom <- function(.) GeomVline
required_aes <- c("x")
calculate <- function(., data, scales, x = NULL, fun, ...) {
center <- fun(data[["x"]])
data.frame(
x = center,
xend = center)
}
})
@tgs
Copy link
Author

tgs commented May 26, 2015

Example usage:

    (ggplot(mtcars)
        + aes(x = mpg)
        + geom_histogram()
        + facet_grid(cyl ~ .)
        + stat_hist_summary(fun = median, colour = "red")
    )

@tgs
Copy link
Author

tgs commented May 27, 2015

This software is in the public domain.

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