Skip to content

Commit 0ce1c74

Browse files
committed
Allow stat_function to work with discrete x
Fixes #1509
1 parent ee5fc6e commit 0ce1c74

File tree

3 files changed

+22
-1
lines changed

3 files changed

+22
-1
lines changed

NEWS.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
## Bug fixes and minor improvements
44

5+
* `stat_function()` once again works with discrete x axes (#1509).
6+
57
* All `\donttest{}` examples run.
68

79
* Removed a superfluous comma in `theme-defaults.r` code (@jschoeley)

R/stat-function.r

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,9 +80,17 @@ StatFunction <- ggproto("StatFunction", Stat,
8080
range <- scales$x$dimension()
8181
xseq <- seq(range[1], range[2], length.out = n)
8282

83+
if (scales$x$is_discrete()) {
84+
x_trans <- xseq
85+
} else {
86+
# For continuous scales, need to back transform from transformed range
87+
# to original values
88+
x_trans <- scales$x$trans$inverse(xseq)
89+
}
90+
8391
data.frame(
8492
x = xseq,
85-
y = do.call(fun, c(list(quote(scales$x$trans$inverse(xseq))), args))
93+
y = do.call(fun, c(list(quote(x_trans)), args))
8694
)
8795
}
8896
)

tests/testthat/test-stats-function.r

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,3 +23,14 @@ test_that("uses scale limits, not data limits", {
2323
expect_false(any(is.na(ret$y)))
2424
expect_false(any(is.na(ret_log$y)))
2525
})
26+
27+
test_that("works with discrete x", {
28+
dat <- data.frame(x = c("a", "b"))
29+
30+
base <- ggplot(dat, aes(x, group = 1)) +
31+
stat_function(fun = as.numeric, geom = "point", n = 2)
32+
ret <- layer_data(base)
33+
34+
expect_equal(ret$x, 1:2)
35+
expect_equal(ret$y, 1:2)
36+
})

0 commit comments

Comments
 (0)