tests/testthat/test-aes-grouping.R

df <- data_frame(
  x = 1:4,
  a = c("a", "a", "b", "b"),
  b = c("a", "b", "a", "b")
)

group <- function(x) as.vector(layer_data(x, 1)$group)
groups <- function(x) vec_unique_count(group(x))


test_that("one group per combination of discrete vars", {
  plot <- ggplot(df, aes(x, x)) + geom_point()
  expect_equal(group(plot), rep(NO_GROUP, 4))

  plot <- ggplot(df, aes(x, a)) + geom_point()
  expect_equal(group(plot), c(1, 1, 2, 2))
  plot <- ggplot(df, aes(x, b)) + geom_point()
  expect_equal(group(plot), c(1, 2, 1, 2))

  plot <- ggplot(df, aes(a, b)) + geom_point()
  expect_equal(groups(plot), 4)
})

test_that("no error for aes(groupS)", {
  df2 <- data_frame(x = df$a, y = df$b, groupS = 1)
  g <- add_group(df2)

  expect_equal(nrow(g), nrow(df2))
  expect_equal(names(g), c("x", "y", "groupS", "group"))
})

test_that("label is not used as a grouping var", {
  plot <- ggplot(df, aes(x, x, label = a)) + geom_point()
  expect_equal(group(plot), rep(NO_GROUP, 4))

  plot <- ggplot(df, aes(x, x, colour = a, label = b)) + geom_point()
  expect_equal(group(plot), c(1, 1, 2, 2))
})

test_that("group aesthetic overrides defaults", {
  plot <- ggplot(df, aes(x, x, group = x)) + geom_point()
  expect_equal(groups(plot), 4)

  plot <- ggplot(df, aes(a, b, group = 1)) + geom_point()
  expect_equal(groups(plot), 1)
})

test_that("group param overrides defaults", {
  plot <- ggplot(df, aes(a, b)) + geom_point(group = 1)
  expect_equal(groups(plot), 1)
})

Try the ggplot2 package in your browser

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

ggplot2 documentation built on June 22, 2024, 11:35 a.m.