1context("stat_summary")
2
3test_that("stat_summary(_bin) work with lambda expressions", {
4  # note: stat_summary and stat_summary_bin both use
5  # make_summary_fun, so this tests both
6
7  dat <- data_frame(
8    x = c(1, 1, 2, 2, 3, 3),
9    y = c(0, 2, 1, 3, 2, 4)
10  )
11
12  p1 <- ggplot(dat, aes(x, y)) +
13    stat_summary(fun.data = mean_se)
14
15
16  # test fun.data
17  p2 <- ggplot(dat, aes(x, y)) +
18    stat_summary(fun.data = ~ {
19      mean <- mean(.x)
20      se <- sqrt(stats::var(.x) / length(.x))
21      data_frame(y = mean, ymin = mean - se, ymax = mean + se)
22    })
23
24  expect_equal(
25    layer_data(p1),
26    layer_data(p2)
27  )
28
29
30  # fun, fun.min, fun.max
31  p3 <- ggplot(dat, aes(x, y)) +
32    stat_summary(
33      fun = ~ mean(.x),
34      fun.min = ~ mean(.x) - sqrt(stats::var(.x) / length(.x)),
35      fun.max = ~ mean(.x) + sqrt(stats::var(.x) / length(.x))
36    )
37
38  expect_equal(
39    layer_data(p1),
40    layer_data(p3)
41  )
42
43})
44
45
46
47
48test_that("stat_summary_(2d|hex) work with lambda expressions", {
49
50  dat <- data_frame(
51    x = c(0, 0, 0, 0, 1, 1, 1, 1),
52    y = c(0, 0, 1, 1, 0, 0, 1, 1),
53    z = c(1, 1, 2, 2, 2, 2, 3, 3)
54  )
55
56
57  # stat_summary_2d
58  p1 <- ggplot(dat, aes(x, y, z = z)) +
59    stat_summary_2d(fun = function(x) mean(x))
60
61  p2 <- ggplot(dat, aes(x, y, z = z)) +
62    stat_summary_2d(fun = ~ mean(.x))
63
64  expect_equal(
65    layer_data(p1),
66    layer_data(p2)
67  )
68
69
70
71  # stat_summary_hex
72  # this plot is a bit funky, but easy to reason through
73  p1 <- ggplot(dat, aes(x, y, z = z)) +
74    stat_summary_hex(fun = function(x) mean(x))
75
76  p2 <- ggplot(dat, aes(x, y, z = z)) +
77    stat_summary_hex(fun = ~ mean(.x))
78
79  expect_equal(
80    layer_data(p1),
81    layer_data(p2)
82  )
83
84})
85