Skip to content

Commit c514c26

Browse files
Fix limits argument of scale_{colour,fill}_manual() (#3685)
Fix #3262
1 parent a8acd82 commit c514c26

File tree

3 files changed

+23
-3
lines changed

3 files changed

+23
-3
lines changed

NEWS.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,9 @@
127127
the upper in the same case by default. If you want old-style full stroking, use
128128
`outlier.type = "legacy"` (#3503, @yutannihilation).
129129

130+
* `scale_manual_*(limits = ...)` now actually limits the scale (#3262,
131+
@yutannihilation).
132+
130133

131134
# ggplot2 3.2.1
132135

R/scale-.r

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -775,11 +775,16 @@ ScaleDiscrete <- ggproto("ScaleDiscrete", Scale,
775775
self$n.breaks.cache <- n
776776
}
777777

778-
if (is.null(names(pal))) {
779-
pal_match <- pal[match(as.character(x), limits)]
780-
} else {
778+
if (is_named(pal)) {
779+
# if pal is named, limit the pal by the names first,
780+
# then limit the values by the pal
781+
idx_nomatch <- is.na(match(names(pal), limits))
782+
pal[idx_nomatch] <- NA
781783
pal_match <- pal[match(as.character(x), names(pal))]
782784
pal_match <- unname(pal_match)
785+
} else {
786+
# if pal is not named, limit the values directly
787+
pal_match <- pal[match(as.character(x), limits)]
783788
}
784789

785790
if (self$na.translate) {

tests/testthat/test-scale-manual.r

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,3 +85,15 @@ test_that("unnamed values match breaks in manual scales", {
8585
s$train(c("data_red", "data_black"))
8686
expect_equal(s$map(c("data_red", "data_black")), c("red", "black"))
8787
})
88+
89+
test_that("limits works (#3262)", {
90+
# named charachter vector
91+
s1 <- scale_colour_manual(values = c("8" = "c", "4" = "a", "6" = "b"), limits = c("4", "8"))
92+
s1$train(c("4", "6", "8"))
93+
expect_equal(s1$map(c("4", "6", "8")), c("a", NA, "c"))
94+
95+
# named charachter vector
96+
s2 <- scale_colour_manual(values = c("c", "a", "b"), limits = c("4", "8"))
97+
s2$train(c("4", "6", "8"))
98+
expect_equal(s2$map(c("4", "6", "8")), c("c", NA, "a"))
99+
})

0 commit comments

Comments
 (0)