Skip to content

Commit

Permalink
Improve labeller() behavior for lookup tables (#5432)
Browse files Browse the repository at this point in the history
  • Loading branch information
92amartins authored Sep 22, 2023
1 parent de7bad6 commit 69e7430
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 1 deletion.
3 changes: 3 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
# ggplot2 (development version)

* `labeller()` now handles unspecified entries from lookup tables
(@92amartins, #4599).

* `fortify.default()` now accepts a data-frame-like object granted the object
exhibits healthy `dim()`, `colnames()`, and `as.data.frame()` behaviors
(@hpages, #5390).
Expand Down
6 changes: 5 additions & 1 deletion R/labeller.R
Original file line number Diff line number Diff line change
Expand Up @@ -450,7 +450,11 @@ labeller <- function(..., .rows = NULL, .cols = NULL,
# Apply named labeller one by one
out <- lapply(names(labels), function(label) {
if (label %in% names(labellers)) {
labellers[[label]](labels[label])[[1]]
# Yield custom labels with any NA replaced with original
lbls <- labellers[[label]](labels[label])[[1]]
ind <- which(is.na(lbls))
lbls[ind] <- .default(labels[label])[[1]][ind]
lbls
} else {
.default(labels[label])[[1]]
}
Expand Down
12 changes: 12 additions & 0 deletions tests/testthat/test-labellers.R
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,15 @@ test_that("labeller function catches overlap in names", {
)
expect_snapshot_error(ggplotGrob(p))
})

test_that("labeller handles badly specified labels from lookup tables", {
df <- data_frame0(am = c(0, 1))
labs <- labeller(am = c("0" = "Automatic", "11" = "Manual"))
expect_equal(labs(df), list(am = c("Automatic", "1")))
})

test_that("labeller allows cherry-pick some labels", {
df <- data_frame0(am = c(0, 1))
labs <- labeller(am = c("0" = "Automatic"))
expect_equal(labs(df), list(am = c("Automatic", "1")))
})

0 comments on commit 69e7430

Please sign in to comment.