diff --git a/NEWS.md b/NEWS.md index e195f78613..c2f6144ac8 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,7 @@ # ggplot2 (development version) +* Make sure `label_bquote()` has access to the calling environment when + evaluating the labels (@thomasp85, #4141) * Fix bug in `annotate_logticks()` that would cause an error when used together with `coord_flip()` (@thomasp85, #3954) diff --git a/R/labeller.r b/R/labeller.r index 099a2d961d..c4f93f0da8 100644 --- a/R/labeller.r +++ b/R/labeller.r @@ -205,6 +205,8 @@ label_bquote <- function(rows = NULL, cols = NULL, rows_quoted <- substitute(rows) has_warned <- FALSE + call_env <- env_parent() + fun <- function(labels) { quoted <- resolve_labeller(rows_quoted, cols_quoted, labels) if (is.null(quoted)) { @@ -225,7 +227,7 @@ label_bquote <- function(rows = NULL, cols = NULL, } params$x <- params[[1]] } - + params <- as_environment(params, call_env) eval(substitute(bquote(expr, params), list(expr = quoted))) } list(do.call("Map", c(list(f = evaluate), labels))) diff --git a/tests/testthat/test-labellers.R b/tests/testthat/test-labellers.R new file mode 100644 index 0000000000..5900e31e4e --- /dev/null +++ b/tests/testthat/test-labellers.R @@ -0,0 +1,9 @@ +context("Labellers") + +test_that("label_bquote has access to functions in the calling environment", { + labels <- data.frame(lab = letters[1:2]) + attr(labels, "facet") <- "wrap" + labeller <- label_bquote(rows = .(paste0(lab, ":"))) + labels_calc <- labeller(labels) + expect_equal(labels_calc[[1]][[1]], "a:") +})