Skip to content
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

Fix limits argument of scale_{colour,fill}_manual() #3685

Merged
Show file tree
Hide file tree
Changes from 6 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
3 changes: 3 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,9 @@
* `stat_summary()` and related functions now support rlang-style lambda functions
(#3568, @dkahle).

* `scale_manual_*(limits = ...)` now actually limits the scale (#3262,
@yutannihilation).


# ggplot2 3.2.1

Expand Down
11 changes: 8 additions & 3 deletions R/scale-.r
Original file line number Diff line number Diff line change
Expand Up @@ -775,11 +775,16 @@ ScaleDiscrete <- ggproto("ScaleDiscrete", Scale,
self$n.breaks.cache <- n
}

if (is.null(names(pal))) {
pal_match <- pal[match(as.character(x), limits)]
} else {
if (is_named(pal)) {
# if pal is named, limit the pal by the names first,
# then limit the values by the pal
idx_nomatch <- is.na(match(names(pal), limits))
pal[idx_nomatch] <- NA
pal_match <- pal[match(as.character(x), names(pal))]
pal_match <- unname(pal_match)
} else {
# if pal is not named, limit the values directly
pal_match <- pal[match(as.character(x), limits)]
}

if (self$na.translate) {
Expand Down
12 changes: 12 additions & 0 deletions tests/testthat/test-scale-manual.r
Original file line number Diff line number Diff line change
Expand Up @@ -85,3 +85,15 @@ test_that("unnamed values match breaks in manual scales", {
s$train(c("data_red", "data_black"))
expect_equal(s$map(c("data_red", "data_black")), c("red", "black"))
})

test_that("limits works (#3262)", {
# named charachter vector
s1 <- scale_colour_manual(values = c("8" = "c", "4" = "a", "6" = "b"), limits = c("4", "8"))
s1$train(c("4", "6", "8"))
expect_equal(s1$map(c("4", "6", "8")), c("a", NA, "c"))

# named charachter vector
s2 <- scale_colour_manual(values = c("c", "a", "b"), limits = c("4", "8"))
s2$train(c("4", "6", "8"))
expect_equal(s2$map(c("4", "6", "8")), c("c", NA, "a"))
})