Skip to content

Commit 53815f8

Browse files
authored
fix stat_contour() for irregular data grids. (#3907)
* fix stat_contour() for irregular data grids. closes #3906. * fix test * additional unit test
1 parent da2388e commit 53815f8

File tree

2 files changed

+25
-6
lines changed

2 files changed

+25
-6
lines changed

R/stat-contour.r

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -206,14 +206,14 @@ xyz_to_isobands <- function(data, breaks) {
206206
#'
207207
isoband_z_matrix <- function(data) {
208208
# Convert vector of data to raster
209-
x_pos <- as.integer((data$x - min(data$x)) / resolution(data$x, FALSE))
210-
y_pos <- as.integer((max(data$y) - data$y) / resolution(data$y, FALSE))
209+
x_pos <- as.integer(factor(data$x, levels = sort(unique(data$x))))
210+
y_pos <- as.integer(factor(data$y, levels = sort(unique(data$y))))
211211

212-
nrow <- max(y_pos) + 1
213-
ncol <- max(x_pos) + 1
212+
nrow <- max(y_pos)
213+
ncol <- max(x_pos)
214214

215215
raster <- matrix(NA_real_, nrow = nrow, ncol = ncol)
216-
raster[cbind(nrow - y_pos, x_pos + 1)] <- data$z
216+
raster[cbind(y_pos, x_pos)] <- data$z
217217

218218
raster
219219
}

tests/testthat/test-stat-contour.R

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,26 @@ test_that("a warning is issued when there is more than one z per x+y", {
1010
test_that("contouring sparse data results in a warning", {
1111
tbl <- data_frame(x = c(1, 27, 32), y = c(1, 1, 30), z = c(1, 2, 3))
1212
p <- ggplot(tbl, aes(x, y, z = z)) + geom_contour()
13-
expect_warning(ggplot_build(p), "Number of x coordinates must match")
13+
expect_warning(ggplot_build(p), "Zero contours were generated")
14+
})
15+
16+
test_that("contouring irregularly spaced data works", {
17+
tbl <- expand.grid(x = c(1, 10, 100, 1000), y = 1:3)
18+
tbl$z <- 1
19+
tbl[c(6, 7), ]$z <- 10
20+
p <- ggplot(tbl, aes(x, y, z = z)) + geom_contour(breaks = c(4, 8))
21+
22+
# we're testing for set equality here because contour lines are not
23+
# guaranteed to start and end at the same point on all architectures
24+
d <- layer_data(p)
25+
d4 <- d[d$level == 4,]
26+
expect_equal(nrow(d4), 7)
27+
expect_setequal(d4$x, c(4, 10, 100, 700))
28+
expect_setequal(d4$y, c(2, 8/3, 4/3))
29+
d8 <- d[d$level == 8,]
30+
expect_equal(nrow(d8), 7)
31+
expect_setequal(d8$x, c(8, 10, 100, 300))
32+
expect_setequal(d8$y, c(2, 20/9, 16/9))
1433
})
1534

1635
test_that("contour breaks can be set manually and by bins and binwidth", {

0 commit comments

Comments
 (0)