forked from tidyverse/ggplot2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgeom-errorbarh.r
79 lines (72 loc) · 2.24 KB
/
geom-errorbarh.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
78
79
#' Horizontal error bars
#'
#' A rotated version of [geom_errorbar()].
#'
#' @eval rd_aesthetics("geom", "errorbarh")
#' @inheritParams layer
#' @inheritParams geom_point
#' @export
#' @examples
#' df <- data.frame(
#' trt = factor(c(1, 1, 2, 2)),
#' resp = c(1, 5, 3, 4),
#' group = factor(c(1, 2, 1, 2)),
#' se = c(0.1, 0.3, 0.3, 0.2)
#' )
#'
#' # Define the top and bottom of the errorbars
#'
#' p <- ggplot(df, aes(resp, trt, colour = group))
#' p + geom_point() +
#' geom_errorbarh(aes(xmax = resp + se, xmin = resp - se))
#' p + geom_point() +
#' geom_errorbarh(aes(xmax = resp + se, xmin = resp - se, height = .2))
geom_errorbarh <- function(mapping = NULL, data = NULL,
stat = "identity", position = "identity",
...,
na.rm = FALSE,
show.legend = NA,
inherit.aes = TRUE) {
layer(
data = data,
mapping = mapping,
stat = stat,
geom = GeomErrorbarh,
position = position,
show.legend = show.legend,
inherit.aes = inherit.aes,
params = list(
na.rm = na.rm,
...
)
)
}
#' @rdname ggplot2-ggproto
#' @format NULL
#' @usage NULL
#' @export
GeomErrorbarh <- ggproto("GeomErrorbarh", Geom,
default_aes = aes(colour = "black", size = 0.5, linetype = 1, height = 0.5,
alpha = NA),
draw_key = draw_key_path,
required_aes = c("xmin", "xmax", "y"),
setup_data = function(data, params) {
data$height <- data$height %||%
params$height %||% (resolution(data$y, FALSE) * 0.9)
transform(data,
ymin = y - height / 2, ymax = y + height / 2, height = NULL
)
},
draw_panel = function(data, panel_params, coord, height = NULL) {
GeomPath$draw_panel(new_data_frame(list(
x = as.vector(rbind(data$xmax, data$xmax, NA, data$xmax, data$xmin, NA, data$xmin, data$xmin)),
y = as.vector(rbind(data$ymin, data$ymax, NA, data$y, data$y, NA, data$ymin, data$ymax)),
colour = rep(data$colour, each = 8),
alpha = rep(data$alpha, each = 8),
size = rep(data$size, each = 8),
linetype = rep(data$linetype, each = 8),
group = rep(1:(nrow(data)), each = 8),
row.names = 1:(nrow(data) * 8)
)), panel_params, coord)
}
)