diff --git a/R/position-nudge.R b/R/position-nudge.R index eaa3070570..ddd58989a0 100644 --- a/R/position-nudge.R +++ b/R/position-nudge.R @@ -47,13 +47,13 @@ PositionNudge <- ggproto("PositionNudge", Position, compute_layer = function(data, params, panel) { # transform only the dimensions for which non-zero nudging is requested - if (params$x != 0) { - if (params$y != 0) { + if (any(params$x != 0)) { + if (any(params$y != 0)) { transform_position(data, function(x) x + params$x, function(y) y + params$y) } else { transform_position(data, function(x) x + params$x, NULL) } - } else if (params$y != 0) { + } else if (any(params$y != 0)) { transform_position(data, NULL, function(y) y + params$y) } else { data # if both x and y are 0 we don't need to transform diff --git a/tests/testthat/test-position-nudge.R b/tests/testthat/test-position-nudge.R index 0ca8342dd3..fa634aa95c 100644 --- a/tests/testthat/test-position-nudge.R +++ b/tests/testthat/test-position-nudge.R @@ -1,6 +1,7 @@ context("position_nudge") test_that("nudging works in both dimensions simultaneously", { + # individual nudge value df <- data_frame(x = 1:3) p <- ggplot(df, aes(x, x, xmax = x, xmin = x, ymax = x, ymin = x)) + @@ -14,6 +15,22 @@ test_that("nudging works in both dimensions simultaneously", { expect_equal(data$y, 3:5) expect_equal(data$ymin, 3:5) expect_equal(data$ymax, 3:5) + + # multiple nudge values, including zero + df <- data_frame(x = c(1, 2, 1)) + + p <- ggplot(df, aes(x, x, xmax = x, xmin = x, ymax = x, ymin = x)) + + geom_point(position = position_nudge(x = c(0, -1, 0), y = c(0, 1, 2))) + + data <- layer_data(p) + + expect_equal(data$x, c(1, 1, 1)) + expect_equal(data$xmin, c(1, 1, 1)) + expect_equal(data$xmax, c(1, 1, 1)) + expect_equal(data$y, c(1, 3, 3)) + expect_equal(data$ymin, c(1, 3, 3)) + expect_equal(data$ymax, c(1, 3, 3)) + }) test_that("nudging works in individual dimensions", { @@ -30,6 +47,17 @@ test_that("nudging works in individual dimensions", { expect_equal(data$xmin, 2:4) expect_equal(data$xmax, 2:4) + # multiple nudge values, including zero + p <- ggplot(df, aes(x = x, xmax = x, xmin = x)) + + layer(geom = Geom, stat = StatIdentity, position = position_nudge(x = c(0, -1, -2))) + + data <- layer_data(p) + + expect_equal(data$x, c(1, 1, 1)) + expect_equal(data$xmin, c(1, 1, 1)) + expect_equal(data$xmax, c(1, 1, 1)) + + # nudging in y # use an empty layer so can test individual aesthetics p <- ggplot(df, aes(y = x, ymax = x, ymin = x)) + @@ -40,4 +68,15 @@ test_that("nudging works in individual dimensions", { expect_equal(data$y, 3:5) expect_equal(data$ymin, 3:5) expect_equal(data$ymax, 3:5) + + # multiple nudge values, including zero + p <- ggplot(df, aes(y = x, ymax = x, ymin = x)) + + layer(geom = Geom, stat = StatIdentity, position = position_nudge(y = c(0, -1, -2))) + + data <- layer_data(p) + + expect_equal(data$y, c(1, 1, 1)) + expect_equal(data$ymin, c(1, 1, 1)) + expect_equal(data$ymax, c(1, 1, 1)) + })