Skip to content

Commit

Permalink
Show NA keys better (#5759)
Browse files Browse the repository at this point in the history
* Account for non-missing values mapping to NA

* add test

* add news bullet
  • Loading branch information
teunbrand authored Mar 18, 2024
1 parent 3d65697 commit dfec855
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 0 deletions.
2 changes: 2 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
* Patterns and gradients are now also enabled in `geom_sf()`
(@teunbrand, #5716).
* `stat_bin()` deals with non-finite breaks better (@teunbrand, #5665).
* When legends detect the presence of values in a layer, `NA` is now detected
if the data contains values outside the given breaks (@teunbrand, #5749).
* `annotate()` now warns about `stat` or `position` arguments (@teunbrand, #5151)

# ggplot2 3.5.0
Expand Down
13 changes: 13 additions & 0 deletions R/guide-legend.R
Original file line number Diff line number Diff line change
Expand Up @@ -649,6 +649,19 @@ keep_key_data <- function(key, data, aes, show) {
for (column in match) {
keep <- keep | key$.value %in% data[[column]]
}

# NA might be included in breaks but originate from non-missing values that
# map to NA instead of *being* NA. We double-check if there are values
# outside the non-missing conventional limits.
is_na <- which(is.na(key$.value) & !keep)
if (length(is_na) > 0) {
na_keep <- FALSE
for (column in match) {
na_keep <- na_keep || !all(data[[column]] %in% key$.value)
}
keep[is_na] <- na_keep
}

keep
}

Expand Down
5 changes: 5 additions & 0 deletions tests/testthat/test-draw-key.R
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,11 @@ test_that("keep_draw_key", {
c(FALSE, TRUE)
)

# Missing values
key <- data_frame0(.value = c("A", "B", NA))
data <- data_frame0(foo = c("A", "B", "C")) # 'C' should count as NA
expect_equal(keep_key_data(key, data, "foo", show = NA), c(TRUE, TRUE, TRUE))

p <- ggplot(data.frame(x = 1:2), aes(x, x)) +
geom_point(
aes(colour = "point", alpha = "point"),
Expand Down

0 comments on commit dfec855

Please sign in to comment.