File: test-geom-quantile.R

package info (click to toggle)
r-cran-ggplot2 3.3.3%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 8,184 kB
  • sloc: sh: 15; makefile: 5
file content (57 lines) | stat: -rw-r--r-- 1,353 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
context("geom-quantile")

test_that("geom_quantile matches quantile regression", {
  set.seed(6531)
  x <- rnorm(10)
  df <- tibble::tibble(
    x = x,
    y = x^2 + 0.5 * rnorm(10)
  )

  ps <- ggplot(df, aes(x, y)) + geom_quantile()

  quants <- c(0.25, 0.5, 0.75)

  pred_rq <- predict(
    quantreg::rq(y ~ x,
      tau = quants,
      data = df
    ),
    data_frame(
      x = seq(min(x), max(x), length.out = 100)
    )
  )

  pred_rq <- cbind(seq(min(x), max(x), length.out = 100), pred_rq)
  colnames(pred_rq) <- c("x", paste("Q", quants * 100, sep = "_"))

  # pred_rq is a matrix; convert it to data.frame so that it can be compared
  pred_rq <- as.data.frame(pred_rq)

  ggplot_data <- layer_data(ps)

  pred_rq_test_25 <- pred_rq[, c("x", "Q_25")]
  colnames(pred_rq_test_25) <- c("x", "y")

  # Use expect_equivalent() to ignore rownames
  expect_equivalent(
    ggplot_data[ggplot_data$quantile == 0.25, c("x", "y")],
    pred_rq_test_25
  )

  pred_rq_test_50 <- pred_rq[, c("x", "Q_50")]
  colnames(pred_rq_test_50) <- c("x", "y")

  expect_equivalent(
    ggplot_data[ggplot_data$quantile == 0.5, c("x", "y")],
    pred_rq_test_50
  )

  pred_rq_test_75 <- pred_rq[, c("x", "Q_75")]
  colnames(pred_rq_test_75) <- c("x", "y")

  expect_equivalent(
    ggplot_data[ggplot_data$quantile == 0.75, c("x", "y")],
    pred_rq_test_75
  )
})