-
Notifications
You must be signed in to change notification settings - Fork 1
/
geom_mirrored_histogram.R
77 lines (76 loc) · 2.15 KB
/
geom_mirrored_histogram.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#' Create mirrored histograms
#'
#' @inheritParams ggplot2::geom_histogram
#'
#' @return a geom
#' @export
#'
#' @examples
#' library(ggplot2)
#' ggplot(nhefs_weights, aes(.fitted)) +
#' geom_mirror_histogram(
#' aes(group = qsmk),
#' bins = 50
#' ) +
#' geom_mirror_histogram(
#' aes(fill = qsmk, weight = w_ate),
#' bins = 50,
#' alpha = 0.5
#' ) +
#' scale_y_continuous(labels = abs)
geom_mirror_histogram <- function(
mapping = NULL,
data = NULL,
position = "stack",
...,
binwidth = NULL,
bins = NULL,
na.rm = FALSE,
orientation = NA,
show.legend = NA,
inherit.aes = TRUE
) {
ggplot2::geom_histogram(
mapping = mapping,
data = data,
stat = StatMirrorCount,
position = position,
...,
binwidth = binwidth,
bins = bins,
na.rm = na.rm,
orientation = orientation,
show.legend = show.legend,
inherit.aes = inherit.aes
)
}
StatMirrorCount <- ggplot2::ggproto(
"StatMirrorCount",
ggplot2::StatBin,
compute_group = function(data, scales, binwidth = NULL, bins = NULL,
center = NULL, boundary = NULL,
closed = c("right", "left"), pad = FALSE,
breaks = NULL, flipped_aes = FALSE,
origin = NULL, right = NULL, drop = NULL) {
group <- unique(data$group)
data <- ggplot2::StatBin$compute_group(data = data, scales = scales, binwidth = binwidth, bins = bins,
center = center, boundary = boundary,
closed = closed, pad = pad,
breaks = breaks, flipped_aes = flipped_aes,
origin = origin, right = right, drop = drop)
if (group == 1) {
data$count <- -data$count
} else if (group > 2) {
abort(
"Groups of three or greater not supported in `geom_mirror_histogram()`"
)
} else if (group == -1) {
abort(c(
"No group detected.",
"*" = "Do you need to use {.var aes(group = ...)} \\
with your grouping variable?"
))
}
data
}
)