Skip to content

Commit fd35a9e

Browse files
authored
Fix for raster resolution (#5412)
* coord transformation after determining positions * add tolerance to `resolution()` * Add tests * add news bullet
1 parent 0e72d95 commit fd35a9e

File tree

6 files changed

+79
-3
lines changed

6 files changed

+79
-3
lines changed

NEWS.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,11 @@
11
# ggplot2 (development version)
22

3+
* `resolution()` has a small tolerance, preventing spuriously small resolutions
4+
due to rounding errors (@teunbrand, #2516).
5+
36
* `stage()` now works correctly, even with aesthetics that do not have scales
47
(#5408)
8+
59
* `labeller()` now handles unspecified entries from lookup tables
610
(@92amartins, #4599).
711

R/geom-raster.R

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,12 +92,13 @@ GeomRaster <- ggproto("GeomRaster", Geom,
9292
"{.fn {snake_class(self)}} only works with {.fn coord_cartesian}"
9393
))
9494
}
95-
data <- coord$transform(data, panel_params)
9695

9796
# Convert vector of data to raster
9897
x_pos <- as.integer((data$x - min(data$x)) / resolution(data$x, FALSE))
9998
y_pos <- as.integer((data$y - min(data$y)) / resolution(data$y, FALSE))
10099

100+
data <- coord$transform(data, panel_params)
101+
101102
nrow <- max(y_pos) + 1
102103
ncol <- max(x_pos) + 1
103104

R/utilities-resolution.R

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ resolution <- function(x, zero = TRUE) {
2727
if (zero) {
2828
x <- unique0(c(0, x))
2929
}
30-
31-
min(diff(sort(x)))
30+
d <- diff(sort(x))
31+
tolerance <- sqrt(.Machine$double.eps)
32+
min(d[d > tolerance])
3233
}
Lines changed: 60 additions & 0 deletions
Loading

tests/testthat/test-geom-raster.R

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,4 +68,11 @@ test_that("geom_raster draws correctly", {
6868
expect_doppelganger("irregular categorical",
6969
ggplot(df, aes(x, y, fill = factor(col))) + geom_raster()
7070
)
71+
72+
# Categorical axes -----------------------------------------------------------
73+
74+
df <- expand.grid(x = c("A", "B"), y = c("C", "D"))
75+
expect_doppelganger("discrete positions",
76+
ggplot(df, aes(x, y, fill = interaction(x, y))) + geom_raster()
77+
)
7178
})

tests/testthat/test-utilities.R

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,4 +173,7 @@ test_that("resolution() gives correct answers", {
173173
expect_equal(resolution(mapped_discrete(c(4, 6))), 1L)
174174
expect_equal(resolution(c(0, 0)), 1L)
175175
expect_equal(resolution(c(0.5, 1.5), zero = TRUE), 0.5)
176+
177+
# resolution has a tolerance
178+
expect_equal(resolution(c(1, 1 + 1000 * .Machine$double.eps, 2)), 1)
176179
})

0 commit comments

Comments
 (0)