Skip to content

Commit 7a6c1cb

Browse files
committed
check for unknown labels
1 parent b57aaa7 commit 7a6c1cb

File tree

3 files changed

+32
-3
lines changed

3 files changed

+32
-3
lines changed

R/labels.R

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,8 @@ update_labels <- function(p, labels) {
1818

1919
# Called in `ggplot_build()` to set default labels not specified by user.
2020
setup_plot_labels <- function(plot, layers, data) {
21-
# Initiate from user-defined labels
22-
labels <- plot$labels
21+
# Initiate empty labels
22+
labels <- list()
2323

2424
# Find labels from every layer
2525
for (i in seq_along(layers)) {
@@ -63,7 +63,26 @@ setup_plot_labels <- function(plot, layers, data) {
6363
labels <- defaults(labels, current)
6464
}
6565
}
66-
labels
66+
67+
# Warn for spurious labels that don't have a mapping.
68+
# Note: sometimes, 'x' and 'y' might not have a mapping, like in
69+
# `geom_function()`. We can display these labels anyway, so we include them.
70+
plot_labels <- plot$labels
71+
known_labels <- c(names(labels), fn_fmls_names(labs), "x", "y")
72+
extra_labels <- setdiff(names(plot_labels), known_labels)
73+
74+
if (length(extra_labels) > 0) {
75+
extra_labels <- paste0(
76+
"{.code ", extra_labels, " = \"", plot_labels[extra_labels], "\"}"
77+
)
78+
names(extra_labels) <- rep("*", length(extra_labels))
79+
cli::cli_warn(c(
80+
"Ignoring unknown labels:",
81+
extra_labels
82+
))
83+
}
84+
85+
defaults(plot_labels, labels)
6786
}
6887

6988
#' Modify axis, legend, and plot labels

tests/testthat/_snaps/labels.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,11 @@
1212
* foo = "bar"
1313
i Did you misspell an argument name?
1414

15+
# warnings are thrown for unknown labels
16+
17+
Ignoring unknown labels:
18+
* `foo = "bar"`
19+
1520
# plot.tag.position rejects invalid input
1621

1722
The `plot.tag.position` theme element must be a <character/numeric/integer> object.

tests/testthat/test-labels.R

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,11 @@ test_that("get_alt_text checks dots", {
9393
expect_snapshot_warning(get_alt_text(ggplot(), foo = "bar"))
9494
})
9595

96+
test_that("warnings are thrown for unknown labels", {
97+
p <- ggplot(mtcars, aes(mpg, disp)) + geom_point() + labs(foo = 'bar')
98+
expect_snapshot_warning(ggplot_build(p))
99+
})
100+
96101
test_that("plot.tag.position rejects invalid input", {
97102
p <- ggplot(mtcars, aes(mpg, disp)) + geom_point() + labs(tag = "Fig. A)")
98103

0 commit comments

Comments
 (0)