tests/testthat/test_scale_cyclical.R

context("scale_*_cyclical")


test_that("basic tests", {
  df <- data.frame(x=sample(1:26), y=sample(1:26),
                   letters)
  p <- ggplot(df, aes(x, y, label=letters, color=letters)) + geom_text() +
    scale_color_cyclical(values = c("#F00000", "#0000F0"))
  d <- layer_data(p)

  # make sure color pattern repeats as expected
  expect_equal(d$colour, rep(c("#F00000", "#0000F0"), 13))

  # make sure there is no legend being generated
  # in ggplot2 >= 3.5.0 legend structure in gtable changed
  if ("get_guide_data" %in% getNamespaceExports("ggplot2")) {
    expect_null(get_guide_data(p, "colour"))
  } else {
    expect_equal("guide-box" %in% ggplotGrob(p)$layout$name, FALSE)
  }

  # once again, different aesthetic, different cyclical pattern, now with legend
  p <- ggplot(df, aes(x, y, label=letters, color=factor(x))) + geom_text() +
    scale_color_cyclical(values = c("#F00000", "#0000F0", "#F0F000"), guide = "legend")
  d <- layer_data(p)

  # make sure color pattern repeats as expected
  expect_equal(d$colour[order(d$x)], rep(c("#F00000", "#0000F0", "#F0F000"), 9)[1:26])

  # make sure there is a legend
  # in ggplot2 >= 3.5.0 legend structure in gtable changed
  if ("get_guide_data" %in% getNamespaceExports("ggplot2")) {
    expect_s3_class(get_guide_data(p, "colour"), "data.frame")
  } else {
    expect_equal("guide-box" %in% ggplotGrob(p)$layout$name, TRUE)
  }

  # test that breaks must match labels
  expect_error(
    ggplot(df, aes(x, y, label=letters, color=factor(x))) + geom_text() +
      scale_color_cyclical(values = c("#F00000", "#0000F0", "#F0F000"),
                           breaks = c(1, 2, 3),
                           labels = c("red", "blue")),
    "`breaks` and `labels` must have the same length")

  # test that legend is omitted if breaks are manually set to NULL, even when legend is switched on
  p <- ggplot(df, aes(x, y, label=letters, color=factor(x))) + geom_text() +
    scale_color_cyclical(values = c("#F00000", "#0000F0", "#F0F000"), breaks = NULL, guide = "legend")
  expect_equal("guide-box" %in% ggplotGrob(p)$layout$name, FALSE)

})


# Visual tests ------------------------------------------------------------
test_that("visual appearance of scale_*_cyclical", {
  df <- data.frame(x=1:30, y=1:30)
  p <- ggplot(df, aes(x, y, fill = factor(x))) + geom_point(shape = 21, size = 3) +
    scale_fill_cyclical(values = c("#F00000", "#00F000", "#0000F0"))
  expect_doppelganger("scale_fill_cyclical red-green-blue dots, no legend", p)

  p <- ggplot(df, aes(x, y, color = factor(x))) + geom_point(size = 3) +
    scale_color_cyclical(values = c("#F00000", "#00F000", "#0000F0"), guide = "legend")
  expect_doppelganger("scale_fill_cyclical red-green-blue dots, with legend", p)

})

Try the ggridges package in your browser

Any scripts or data that you put into this service are public.

ggridges documentation built on May 29, 2024, 9:53 a.m.