Created
May 26, 2015 22:20
-
-
Save tgs/7aca6b70719bc5e2e796 to your computer and use it in GitHub Desktop.
Add median to ggplot2 histogram
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
}) |
Example usage:
(ggplot(mtcars)
+ aes(x = mpg)
+ geom_histogram()
+ facet_grid(cyl ~ .)
+ stat_hist_summary(fun = median, colour = "red")
)
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
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.