@@ -29,6 +29,7 @@ stat_function <- function(mapping = NULL, data = NULL,
29
29
if (! is.null(data )) {
30
30
warn(" `data` is not used by stat_function()" )
31
31
}
32
+ data <- ensure_nonempty_data
32
33
33
34
layer(
34
35
data = data ,
@@ -57,15 +58,21 @@ StatFunction <- ggproto("StatFunction", Stat,
57
58
default_aes = aes(y = after_scale(y )),
58
59
59
60
compute_group = function (data , scales , fun , xlim = NULL , n = 101 , args = list ()) {
60
- range <- xlim %|| % scales $ x $ dimension()
61
- xseq <- seq(range [1 ], range [2 ], length.out = n )
62
-
63
- if (scales $ x $ is_discrete()) {
61
+ if (is.null(scales $ x )) {
62
+ range <- xlim %|| % c(0 , 1 )
63
+ xseq <- seq(range [1 ], range [2 ], length.out = n )
64
64
x_trans <- xseq
65
65
} else {
66
- # For continuous scales, need to back transform from transformed range
67
- # to original values
68
- x_trans <- scales $ x $ trans $ inverse(xseq )
66
+ range <- xlim %|| % scales $ x $ dimension()
67
+ xseq <- seq(range [1 ], range [2 ], length.out = n )
68
+
69
+ if (scales $ x $ is_discrete()) {
70
+ x_trans <- xseq
71
+ } else {
72
+ # For continuous scales, need to back transform from transformed range
73
+ # to original values
74
+ x_trans <- scales $ x $ trans $ inverse(xseq )
75
+ }
69
76
}
70
77
71
78
if (is.formula(fun )) fun <- as_function(fun )
@@ -82,3 +89,15 @@ StatFunction <- ggproto("StatFunction", Stat,
82
89
))
83
90
}
84
91
)
92
+
93
+ # Convenience function used by `stat_function()` and
94
+ # `geom_function()` to convert empty input data into
95
+ # non-empty input data without touching any non-empty
96
+ # input data that may have been provided.
97
+ ensure_nonempty_data <- function (data ) {
98
+ if (empty(data )) {
99
+ new_data_frame(list (group = 1 ), n = 1 )
100
+ } else {
101
+ data
102
+ }
103
+ }
0 commit comments