diff --git a/NEWS.md b/NEWS.md index 840964dbe2..8b9c46c7ea 100644 --- a/NEWS.md +++ b/NEWS.md @@ -15,6 +15,9 @@ * Patterns and gradients are now also enabled in `geom_sf()` (@teunbrand, #5716). * `stat_bin()` deals with non-finite breaks better (@teunbrand, #5665). +* Fixed bug in `guide_bins()` and `guide_coloursteps()` where discrete breaks, + such as the levels produced by `cut()`, were ordered incorrectly + (@teunbrand, #5757). * Theme elements that do not exist now throw warnings instead of errors (#5719). * Fixed bug in `coord_radial()` where full circles were not treated as such (@teunbrand, #5750). diff --git a/R/guide-bins.R b/R/guide-bins.R index 6f253aa0d6..c5f39c9490 100644 --- a/R/guide-bins.R +++ b/R/guide-bins.R @@ -333,8 +333,9 @@ parse_binned_breaks = function(scale, breaks = scale$get_breaks(), if (length(breaks) == 0) { return(NULL) } - breaks <- sort(breaks) + if (is.numeric(breaks)) { + breaks <- sort(breaks) limits <- scale$get_limits() if (!is.numeric(scale$breaks)) { breaks <- breaks[!breaks %in% limits] diff --git a/tests/testthat/test-guides.R b/tests/testthat/test-guides.R index f1344df5b6..f1a9f613d5 100644 --- a/tests/testthat/test-guides.R +++ b/tests/testthat/test-guides.R @@ -501,6 +501,34 @@ test_that("empty guides are dropped", { expect_equal(lengths(guides, use.names = FALSE), rep(0, 5)) }) +test_that("bins can be parsed by guides for all scale types", { + + breaks <- c(90, 100, 200, 300) + limits <- c(0, 1000) + + sc <- scale_colour_continuous(breaks = breaks) + sc$train(limits) + + expect_equal(parse_binned_breaks(sc)$breaks, breaks) + + sc <- scale_colour_binned(breaks = breaks) + sc$train(limits) + + expect_equal(parse_binned_breaks(sc)$breaks, breaks) + + # Note: discrete binned breaks treats outer breaks as limits + cut <- cut(c(0, 95, 150, 250, 1000), breaks = breaks) + + sc <- scale_colour_discrete() + sc$train(cut) + + parsed <- parse_binned_breaks(sc) + expect_equal( + sort(c(parsed$limits, parsed$breaks)), + breaks + ) +}) + # Visual tests ------------------------------------------------------------ test_that("axis guides are drawn correctly", {