From 3da498bf6119fc1cd217bee26c084107e122a619 Mon Sep 17 00:00:00 2001 From: Teun van den Brand Date: Wed, 3 Jul 2024 13:19:20 +0200 Subject: [PATCH 1/3] capture `n.breaks` parameter upon initialisation --- R/axis-secondary.R | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/R/axis-secondary.R b/R/axis-secondary.R index e535b1a95a..2999bd79b5 100644 --- a/R/axis-secondary.R +++ b/R/axis-secondary.R @@ -188,7 +188,13 @@ AxisSecondary <- ggproto("AxisSecondary", NULL, if (scale$is_discrete()) { self$breaks <- scale$get_breaks() } else { - self$breaks <- scale$get_transformation()$breaks + breaks <- scale$get_transformation()$breaks + n_breaks <- scale$n.breaks + if (!is.null(n_breaks) && "n" %in% fn_fmls_names(breaks)) { + self$breaks <- function(x) breaks(x, n = n_breaks) + } else { + self$breaks <- breaks + } } } if (is.derived(self$labels)) self$labels <- scale$labels From ced50fcfc0fe669ee089133ca11237e9f976ded9 Mon Sep 17 00:00:00 2001 From: Teun van den Brand Date: Wed, 3 Jul 2024 14:35:29 +0200 Subject: [PATCH 2/3] add test --- tests/testthat/test-sec-axis.R | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/tests/testthat/test-sec-axis.R b/tests/testthat/test-sec-axis.R index 2b8fde0d94..08c8498ec1 100644 --- a/tests/testthat/test-sec-axis.R +++ b/tests/testthat/test-sec-axis.R @@ -400,3 +400,22 @@ test_that("discrete scales can have secondary axes", { expect_equal(y$.value, c(1.5, 2.5), ignore_attr = TRUE) expect_equal(y$.label, c("grault", "garply")) }) + +test_that("n.breaks is respected by secondary axes (#4483)", { + + b <- ggplot_build( + ggplot(data.frame(x = c(0, 10)), aes(x, x)) + + scale_y_continuous( + n.breaks = 11, + sec.axis = sec_axis(~.x*100) + ) + ) + + # We get scale breaks via guide data + prim <- get_guide_data(b, "y") + sec <- get_guide_data(b, "y.sec") + + expect_equal(prim$.value, sec$.value) # .value is in primary scale + expect_equal(prim$.label, as.character(seq(0, 10, length.out = 11))) + expect_equal(sec$.label, as.character(seq(0, 1000, length.out = 11))) +}) From 9dcb04f9c4865dedda807e8dfc4bbe4d93d3cea6 Mon Sep 17 00:00:00 2001 From: Teun van den Brand Date: Wed, 3 Jul 2024 14:37:54 +0200 Subject: [PATCH 3/3] add news bullet --- NEWS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/NEWS.md b/NEWS.md index d553c7f924..10bae11d84 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,6 @@ # ggplot2 (development version) +* Secondary axes respect `n.breaks` setting in continuous scales (@teunbrand, #4483). * `stat_bin()` now accepts functions for argument `breaks` (@aijordan, #4561) * (internal) The plot's layout now has a coord parameter that is used to prevent setting up identical panel parameters (#5427)