@@ -104,7 +104,10 @@ PositionDodge <- ggproto("PositionDodge", Position,
104
104
preserve = " total" ,
105
105
orientation = " x" ,
106
106
reverse = NULL ,
107
+ default_aes = aes(order = NULL ),
108
+
107
109
setup_params = function (self , data ) {
110
+
108
111
flipped_aes <- has_flipped_aes(data , default = self $ orientation == " y" )
109
112
check_required_aesthetics(
110
113
if (flipped_aes ) " y|ymin" else " x|xmin" ,
@@ -139,9 +142,22 @@ PositionDodge <- ggproto("PositionDodge", Position,
139
142
140
143
setup_data = function (self , data , params ) {
141
144
data <- flip_data(data , params $ flipped_aes )
145
+
142
146
if (! " x" %in% names(data ) && all(c(" xmin" , " xmax" ) %in% names(data ))) {
143
147
data $ x <- (data $ xmin + data $ xmax ) / 2
144
148
}
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
+ }
145
161
flip_data(data , params $ flipped_aes )
146
162
},
147
163
@@ -179,7 +195,7 @@ pos_dodge <- function(df, width, n = NULL) {
179
195
180
196
# Have a new group index from 1 to number of groups.
181
197
# 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 )
183
199
184
200
# Find the center for each group, then use that to calculate xmin and xmax
185
201
df $ x <- df $ x + width * ((groupidx - 0.5 ) / n - 0.5 )
@@ -188,3 +204,7 @@ pos_dodge <- function(df, width, n = NULL) {
188
204
189
205
df
190
206
}
207
+
208
+ match_sorted <- function (x , y = x , ... ) {
209
+ vec_match(x , vec_sort(unique0(y ), ... ))
210
+ }
0 commit comments