Skip to content

Commit

Permalink
Use syntax compatible with R3.1/3.2
Browse files Browse the repository at this point in the history
  • Loading branch information
hadley committed Oct 31, 2017
1 parent 2d89fff commit 4e88fc7
Showing 1 changed file with 15 additions and 12 deletions.
27 changes: 15 additions & 12 deletions R/position-dodge2.r
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ position_dodge2 <- function(width = NULL, preserve = c("single", "total"),
preserve = match.arg(preserve),
padding = padding,
reverse = reverse
)
)
}

#' @rdname ggplot2-ggproto
Expand All @@ -22,7 +22,7 @@ PositionDodge2 <- ggproto("PositionDodge2", PositionDodge,
preserve = "single",
padding = 0.1,
reverse = FALSE,

setup_params = function(self, data) {
if (is.null(data$xmin) && is.null(data$xmax) && is.null(self$width)) {
warning("Width not defined. Set with `position_dodge2(width = ?)`",
Expand All @@ -44,7 +44,7 @@ PositionDodge2 <- ggproto("PositionDodge2", PositionDodge,
reverse = self$reverse
)
},

compute_panel = function(data, params, scales) {
collide2(
data,
Expand All @@ -64,12 +64,12 @@ pos_dodge2 <- function(df, width, n = NULL, padding = 0.1) {
if (length(unique(df$group)) == 1) {
return(df)
}

if (!all(c("xmin", "xmax") %in% names(df))) {
df$xmin <- df$x
df$xmax <- df$x
}

# xid represents groups of boxes that share the same position
df$xid <- find_x_overlaps(df)

Expand All @@ -78,7 +78,7 @@ pos_dodge2 <- function(df, width, n = NULL, padding = 0.1) {
# for arbitrary rects it may not be
newx <- (tapply(df$xmin, df$xid, min) + tapply(df$xmax, df$xid, max)) / 2
df$newx <- newx[df$xid]

if (is.null(n)) {
# If n is null, preserve total widths of elements at each position by
# dividing widths by the number of elements at that position
Expand All @@ -87,7 +87,7 @@ pos_dodge2 <- function(df, width, n = NULL, padding = 0.1) {
} else {
df$new_width <- (df$xmax - df$xmin) / n
}

df$xmin <- df$x - (df$new_width / 2)
df$xmax <- df$x + (df$new_width / 2)

Expand All @@ -96,8 +96,8 @@ pos_dodge2 <- function(df, width, n = NULL, padding = 0.1) {
list(size = df$new_width),
list(newx = df$newx),
sum
)
)

# Starting xmin for each group of elements
starts <- group_sizes$newx - (group_sizes$size / 2)

Expand All @@ -115,14 +115,17 @@ pos_dodge2 <- function(df, width, n = NULL, padding = 0.1) {
if (!any(duplicated(df$xid))) {
return(df)
}

# Shrink elements to add space between them
df$pad_width <- df$new_width * (1 - padding)
df$xmin <- df$x - (df$pad_width / 2)
df$xmax <- df$x + (df$pad_width / 2)

df[, c("xid", "newx", "new_width", "pad_width")] <- NULL

df$xid <- NULL
df$newx <- NULL
df$new_width <- NULL
df$pad_width <- NULL

df
}

Expand Down

0 comments on commit 4e88fc7

Please sign in to comment.