Skip to content

Commit 2f270c0

Browse files
committed
Improve stat_ecdf padding.
Fixes #1467
1 parent 5023b79 commit 2f270c0

File tree

3 files changed

+19
-21
lines changed

3 files changed

+19
-21
lines changed

NEWS.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
# ggplot2 2.0.0.9000
22

3+
* `stat_ecdf()` does a better job of adding padding to -Inf/Inf, and gains
4+
an argument `pad` to suppress the padding if not needed (#1467).
5+
36
* Multipanel empty data is correctly plotted, rather than throwing an unhelpful
47
error (#1445).
58

R/stat-ecdf.r

Lines changed: 11 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
#' a warning. If \code{TRUE} silently removes missing values.
66
#' @param n if NULL, do not interpolate. If not NULL, this is the number
77
#' of points to interpolate with.
8+
#' @param pad If \code{TRUE}, pad the ecdf with additional points (-Inf, 0)
9+
#' and (Inf, 1)
810
#' @section Computed variables:
911
#' \describe{
1012
#' \item{x}{x in data}
@@ -22,7 +24,8 @@
2224
#' ggplot(df, aes(x, colour = g)) + stat_ecdf()
2325
#' }
2426
stat_ecdf <- function(mapping = NULL, data = NULL, geom = "step",
25-
position = "identity", n = NULL, na.rm = FALSE,
27+
position = "identity", n = NULL,
28+
pad = TRUE, na.rm = FALSE,
2629
show.legend = NA, inherit.aes = TRUE, ...) {
2730
layer(
2831
data = data,
@@ -46,31 +49,20 @@ stat_ecdf <- function(mapping = NULL, data = NULL, geom = "step",
4649
#' @usage NULL
4750
#' @export
4851
StatEcdf <- ggproto("StatEcdf", Stat,
49-
compute_group = function(data, scales, n = NULL) {
50-
52+
compute_group = function(data, scales, n = NULL, pad = TRUE) {
5153
# If n is NULL, use raw values; otherwise interpolate
5254
if (is.null(n)) {
53-
xvals <- unique(data$x)
55+
x <- unique(data$x)
5456
} else {
55-
xvals <- seq(min(data$x), max(data$x), length.out = n)
57+
x <- seq(min(data$x), max(data$x), length.out = n)
5658
}
5759

58-
y <- ecdf(data$x)(xvals)
59-
60-
# make point with y = 0, from plot.stepfun
61-
rx <- range(xvals)
62-
if (length(xvals) > 1L) {
63-
dr <- max(0.08 * diff(rx), median(diff(xvals)))
64-
} else {
65-
dr <- abs(xvals)/16
60+
if (pad) {
61+
x <- c(-Inf, x, Inf)
6662
}
63+
y <- ecdf(data$x)(x)
6764

68-
x0 <- rx[1] - dr
69-
x1 <- rx[2] + dr
70-
y0 <- 0
71-
y1 <- 1
72-
73-
data.frame(x = c(x0, xvals, x1), y = c(y0, y, y1))
65+
data.frame(x = x, y = y)
7466
},
7567

7668
default_aes = aes(y = ..y..),

man/stat_ecdf.Rd

Lines changed: 5 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)