diff --git a/NEWS.md b/NEWS.md index fac6706ae8..cd4ed0771d 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). * Layers can have names (@teunbrand, #4066). * (internal) improvements to `pal_qualitative()` (@teunbrand, #5013) * `coord_radial(clip = "on")` clips to the panel area when the graphics device 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 diff --git a/tests/testthat/test-sec-axis.R b/tests/testthat/test-sec-axis.R index 56a788b469..02846e9f81 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))) +})