Skip to content

Commit

Permalink
coord_trans() now generates a warning when a transformation results…
Browse files Browse the repository at this point in the history
… in x or y values being non-finite (tidyverse#2147).
  • Loading branch information
foo-bar-baz-qux committed Jul 21, 2017
1 parent 331977e commit 1564029
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 2 deletions.
19 changes: 17 additions & 2 deletions R/coord-transform.r
Original file line number Diff line number Diff line change
Expand Up @@ -119,8 +119,12 @@ CoordTrans <- ggproto("CoordTrans", Coord,
trans_x <- function(data) transform_value(self$trans$x, data, panel_params$x.range)
trans_y <- function(data) transform_value(self$trans$y, data, panel_params$y.range)

data <- transform_position(data, trans_x, trans_y)
transform_position(data, squish_infinite, squish_infinite)
new_data <- transform_position(data, trans_x, trans_y)

warn_new_infinites(data$x, new_data$x, "x")
warn_new_infinites(data$y, new_data$y, "y")

transform_position(new_data, squish_infinite, squish_infinite)
},

setup_panel_params = function(self, scale_x, scale_y, params = list()) {
Expand Down Expand Up @@ -174,3 +178,14 @@ train_trans <- function(scale, limits, trans, name) {
names(out) <- paste(name, names(out), sep = ".")
out
}

# Generate warning when finite values are transformed into infinite values
#
# @param old_values A vector of pre-transformation values.
# @param new_values A vector of post-transformation values.
# @param axis Which axis the values originate from (e.g. x, y).
warn_new_infinites <- function(old_values, new_values, axis) {
if (any(is.finite(old_values) & !is.finite(new_values))) {
warning("Transformation introduced infinite values in ", axis, "-axis", call. = FALSE)
}
}
22 changes: 22 additions & 0 deletions tests/testthat/test-coord-transform.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
context("coord_trans")

test_that("warnings are generated when cord_trans() results in new infinite values", {
p <- ggplot(head(diamonds, 20)) +
geom_bar(aes(x = cut)) +
coord_trans(y = "log10")

p2 <- ggplot(data.frame(a = c(1, 2, 0), b = c(10, 6, 4)), aes(a, b)) +
geom_point() +
coord_trans(x = "log")

expect_warning(ggplot_gtable(ggplot_build(p)), "Transformation introduced infinite values in y-axis")
expect_warning(ggplot_gtable(ggplot_build(p2)), "Transformation introduced infinite values in x-axis")
})

test_that("no warnings are generated when original data has Inf values, but no new Inf values created from the transformation", {
p <- ggplot(data.frame(x = c(-Inf, 2, 0), y = c(Inf, 6, 4)), aes(x, y)) +
geom_point() +
coord_trans(x = 'identity')

expect_silent(benchplot(p))
})

0 comments on commit 1564029

Please sign in to comment.