Skip to content

Commit dfec855

Browse files
authored
Show NA keys better (#5759)
* Account for non-missing values mapping to NA * add test * add news bullet
1 parent 3d65697 commit dfec855

File tree

3 files changed

+20
-0
lines changed

3 files changed

+20
-0
lines changed

NEWS.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@
1010
* Patterns and gradients are now also enabled in `geom_sf()`
1111
(@teunbrand, #5716).
1212
* `stat_bin()` deals with non-finite breaks better (@teunbrand, #5665).
13+
* When legends detect the presence of values in a layer, `NA` is now detected
14+
if the data contains values outside the given breaks (@teunbrand, #5749).
1315
* `annotate()` now warns about `stat` or `position` arguments (@teunbrand, #5151)
1416

1517
# ggplot2 3.5.0

R/guide-legend.R

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -649,6 +649,19 @@ keep_key_data <- function(key, data, aes, show) {
649649
for (column in match) {
650650
keep <- keep | key$.value %in% data[[column]]
651651
}
652+
653+
# NA might be included in breaks but originate from non-missing values that
654+
# map to NA instead of *being* NA. We double-check if there are values
655+
# outside the non-missing conventional limits.
656+
is_na <- which(is.na(key$.value) & !keep)
657+
if (length(is_na) > 0) {
658+
na_keep <- FALSE
659+
for (column in match) {
660+
na_keep <- na_keep || !all(data[[column]] %in% key$.value)
661+
}
662+
keep[is_na] <- na_keep
663+
}
664+
652665
keep
653666
}
654667

tests/testthat/test-draw-key.R

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,11 @@ test_that("keep_draw_key", {
9696
c(FALSE, TRUE)
9797
)
9898

99+
# Missing values
100+
key <- data_frame0(.value = c("A", "B", NA))
101+
data <- data_frame0(foo = c("A", "B", "C")) # 'C' should count as NA
102+
expect_equal(keep_key_data(key, data, "foo", show = NA), c(TRUE, TRUE, TRUE))
103+
99104
p <- ggplot(data.frame(x = 1:2), aes(x, x)) +
100105
geom_point(
101106
aes(colour = "point", alpha = "point"),

0 commit comments

Comments
 (0)