Skip to content

Instantly share code, notes, and snippets.

@tgs
Created May 26, 2015 22:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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

This works for me, but it's my first attempt to do any sort of ggplot2 extension. I'm sure I'm doing something wrong, or at least sideways.

@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