Skip to content

Making copies of trained position scales #6286

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Mar 25, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,8 @@
(@teunbrand, #5093).
* (internal) When `validate_subclass()` fails to find a class directly, it tries
to retrieve the class via constructor functions (@teunbrand).
* (internal) The ViewScale class has a `make_fixed_copy()` method to permit
copying trained position scales (#3441).

# ggplot2 3.5.1

Expand Down
26 changes: 26 additions & 0 deletions R/scale-view.R
Original file line number Diff line number Diff line change
Expand Up @@ -150,5 +150,31 @@ ViewScale <- ggproto("ViewScale", NULL,
}

self$rescale(b)
},
make_fixed_copy = function(self) {
breaks <- self$get_breaks()
minor <- self$get_breaks_minor()
transform <- self$scale$get_transformation()

if (self$scale$is_discrete()) {
limits <- self$get_limits()
} else {
limits <- self$continuous_range
}

if (!is.null(transform)) {
breaks <- transform$inverse(breaks)
minor <- transform$inverse(minor)
}

ggproto(
NULL, self$scale,
breaks = breaks,
minor_breaks = minor,
limits = limits,
expand = c(0, 0, 0, 0),
continuous_limits = self$continuous_range,
train = function (...) NULL
)
}
)
26 changes: 26 additions & 0 deletions tests/testthat/test-scales.R
Original file line number Diff line number Diff line change
Expand Up @@ -748,6 +748,32 @@ test_that("discrete scales work with NAs in arbitrary positions", {

})

test_that("ViewScales can make fixed copies", {

p1 <- ggplot(mpg, aes(drv, displ)) +
geom_boxplot() +
annotate("point", x = 5, y = 10) +
scale_x_discrete(labels = c("four-wheel", "forward", "reverse"))

b1 <- ggplot_build(p1)$layout$panel_params[[1]]

# We build a second plot with the first plot's scales
p2 <- ggplot(mpg, aes(drv, cyl)) +
geom_violin() +
annotate("point", x = 15, y = 100) +
b1$x$make_fixed_copy() +
b1$y$make_fixed_copy()
b2 <- ggplot_build(p2)

# Breaks and labels should respect p1's limits
x <- get_guide_data(b2, "x")
expect_equal(x$x, 0.6:2.6 / diff(b1$x.range))
expect_equal(x$.label, c("four-wheel", "forward", "reverse"))

y <- get_guide_data(b2, "y")
expect_equal(y$y, rescale(seq(2.5, 10, by = 2.5), from = b1$y.range))
})

test_that("discrete scales can map to 2D structures", {

p <- ggplot(mtcars, aes(disp, mpg, colour = factor(cyl))) +
Expand Down
Loading