Skip to content

Commit

Permalink
Fix limits argument of scale_{colour,fill}_manual() (#3685)
Browse files Browse the repository at this point in the history
Fix #3262
  • Loading branch information
yutannihilation authored Jan 6, 2020
1 parent a8acd82 commit c514c26
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 3 deletions.
3 changes: 3 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,9 @@
the upper in the same case by default. If you want old-style full stroking, use
`outlier.type = "legacy"` (#3503, @yutannihilation).

* `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"))
})

0 comments on commit c514c26

Please sign in to comment.