Skip to content

Commit 4fb145f

Browse files
committed
order aesthetic for position_dodge()
1 parent 442a6ac commit 4fb145f

File tree

1 file changed

+21
-1
lines changed

1 file changed

+21
-1
lines changed

R/position-dodge.R

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,10 @@ PositionDodge <- ggproto("PositionDodge", Position,
104104
preserve = "total",
105105
orientation = "x",
106106
reverse = NULL,
107+
default_aes = aes(order = NULL),
108+
107109
setup_params = function(self, data) {
110+
108111
flipped_aes <- has_flipped_aes(data, default = self$orientation == "y")
109112
check_required_aesthetics(
110113
if (flipped_aes) "y|ymin" else "x|xmin",
@@ -139,9 +142,22 @@ PositionDodge <- ggproto("PositionDodge", Position,
139142

140143
setup_data = function(self, data, params) {
141144
data <- flip_data(data, params$flipped_aes)
145+
142146
if (!"x" %in% names(data) && all(c("xmin", "xmax") %in% names(data))) {
143147
data$x <- (data$xmin + data$xmax) / 2
144148
}
149+
150+
data$order <- xtfrm( # xtfrm makes anything 'sortable'
151+
data$order %||% ave(data$group, data$x, data$PANEL, FUN = match_sorted)
152+
)
153+
if (params$reverse) {
154+
data$order <- -data$order
155+
}
156+
if (is.null(params$n)) { # preserve = "total"
157+
data$order <- ave(data$order, data$x, data$PANEL, FUN = match_sorted)
158+
} else { # preserve = "single"
159+
data$order <- match_sorted(data$order)
160+
}
145161
flip_data(data, params$flipped_aes)
146162
},
147163

@@ -179,7 +195,7 @@ pos_dodge <- function(df, width, n = NULL) {
179195

180196
# Have a new group index from 1 to number of groups.
181197
# This might be needed if the group numbers in this set don't include all of 1:n
182-
groupidx <- match(df$group, unique0(df$group))
198+
groupidx <- df$order %||% match_sorted(df$group)
183199

184200
# Find the center for each group, then use that to calculate xmin and xmax
185201
df$x <- df$x + width * ((groupidx - 0.5) / n - 0.5)
@@ -188,3 +204,7 @@ pos_dodge <- function(df, width, n = NULL) {
188204

189205
df
190206
}
207+
208+
match_sorted <- function(x, y = x, ...) {
209+
vec_match(x, vec_sort(unique0(y), ...))
210+
}

0 commit comments

Comments
 (0)