Skip to content

Commit 64666ab

Browse files
committed
find_global looks in better places for scales
1 parent 3e9c42b commit 64666ab

File tree

2 files changed

+26
-6
lines changed

2 files changed

+26
-6
lines changed

R/scales-.r

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -81,20 +81,20 @@ scales_add_defaults <- function(scales, data, aesthetics, env) {
8181
scale_name <- paste("scale", aes, type, sep="_")
8282

8383
# Skip aesthetics with no scales (e.g. group, order, etc)
84-
scale_f <- find_global(scale_name)
84+
scale_f <- find_global(scale_name, env)
8585
if (is.null(scale_f)) next
8686

8787
scales$add(scale_f())
8888
}
8989

9090
}
9191

92-
# Look for object first in global environment and if not found, then in
92+
# Look for object first in parent environment and if not found, then in
9393
# ggplot2 package environment. This makes it possible to override default
94-
# scales by setting them in the default environment.
95-
find_global <- function(name) {
96-
if (exists(name, globalenv())) {
97-
return(get(name, globalenv()))
94+
# scales by setting them in the parent environment.
95+
find_global <- function(name, env) {
96+
if (exists(name, env)) {
97+
return(get(name, env))
9898
}
9999

100100
if (exists(name, "package:ggplot2")) {

inst/tests/test-scales.r

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,3 +126,23 @@ test_that("oob affects position values", {
126126

127127
})
128128

129+
test_that("scales looked for in appropriate place", {
130+
xlabel <- function(x) ggplot_build(x)$panel$x_scales[[1]]$name
131+
p0 <- qplot(mpg, wt, data = mtcars) + scale_x_continuous("0")
132+
expect_equal(xlabel(p0), "0")
133+
134+
scale_x_continuous <- function(...) ggplot2::scale_x_continuous("1")
135+
p1 <- qplot(mpg, wt, data = mtcars)
136+
expect_equal(xlabel(p1), "1")
137+
138+
f <- function() {
139+
scale_x_continuous <- function(...) ggplot2::scale_x_continuous("2")
140+
qplot(mpg, wt, data = mtcars)
141+
}
142+
p2 <- f()
143+
expect_equal(xlabel(p2), "2")
144+
145+
rm(scale_x_continuous)
146+
p4 <- qplot(mpg, wt, data = mtcars)
147+
expect_equal(xlabel(p4), NULL)
148+
})

0 commit comments

Comments
 (0)