Skip to content

Commit 9702e92

Browse files
committed
capture binning logic in function
1 parent 9c8a15d commit 9702e92

File tree

2 files changed

+40
-18
lines changed

2 files changed

+40
-18
lines changed

R/bin.R

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,41 @@ bin_breaks_bins <- function(x_range, bins = 30, center = NULL,
128128

129129
# Compute bins ------------------------------------------------------------
130130

131+
compute_bins <- function(x, scale, breaks = NULL, binwidth = NULL, bins = NULL,
132+
center = NULL, boundary = NULL,
133+
closed = c("right", "left")) {
134+
135+
if (!is.null(breaks)) {
136+
if (is.function(breaks)) {
137+
breaks <- breaks(x)
138+
}
139+
if (!scale$is_discrete()) {
140+
breaks <- scale$transform(breaks)
141+
}
142+
bins <- bin_breaks(breaks, closed)
143+
return(bins)
144+
}
145+
146+
if (!is.null(binwidth)) {
147+
if (is.function(binwidth)) {
148+
binwidth <- binwidth(x)
149+
}
150+
bins <- bin_breaks_width(
151+
scale$dimension(), binwidth,
152+
center = center, boundary = boundary, closed = closed
153+
)
154+
return(bins)
155+
}
156+
157+
if (is.function(bins)) {
158+
bins <- bins(x)
159+
}
160+
bin_breaks_bins(
161+
scale$dimension(), bins,
162+
center = center, boundary = boundary, closed = closed
163+
)
164+
}
165+
131166
bin_vector <- function(x, bins, weight = NULL, pad = FALSE) {
132167
check_object(bins, is_bins, "a {.cls ggplot2_bins} object")
133168

R/stat-bin.R

Lines changed: 5 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -132,24 +132,11 @@ StatBin <- ggproto("StatBin", Stat,
132132
# be listed so parameters are computed correctly
133133
origin = NULL, right = NULL, drop = NULL) {
134134
x <- flipped_names(flipped_aes)$x
135-
if (!is.null(breaks)) {
136-
if (is.function(breaks)) {
137-
breaks <- breaks(data[[x]])
138-
}
139-
if (!scales[[x]]$is_discrete()) {
140-
breaks <- scales[[x]]$transform(breaks)
141-
}
142-
bins <- bin_breaks(breaks, closed)
143-
} else if (!is.null(binwidth)) {
144-
if (is.function(binwidth)) {
145-
binwidth <- binwidth(data[[x]])
146-
}
147-
bins <- bin_breaks_width(scales[[x]]$dimension(), binwidth,
148-
center = center, boundary = boundary, closed = closed)
149-
} else {
150-
bins <- bin_breaks_bins(scales[[x]]$dimension(), bins, center = center,
151-
boundary = boundary, closed = closed)
152-
}
135+
bins <- compute_bins(
136+
data[[x]], scales[[x]],
137+
breaks = breaks, binwidth = binwidth, bins = bins,
138+
center = center, boundary = boundary, closed = closed
139+
)
153140
bins <- bin_vector(data[[x]], bins, weight = data$weight, pad = pad)
154141

155142
keep <- switch(

0 commit comments

Comments
 (0)