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

Show NA keys better #5759

Merged
merged 4 commits into from
Mar 18, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
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
Loading