Skip to content

Commit 397c1c7

Browse files
authored
Mark labels from default mappings and overwrite them if possible (#4414)
1 parent f014bbd commit 397c1c7

File tree

3 files changed

+26
-2
lines changed

3 files changed

+26
-2
lines changed

NEWS.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
# ggplot2 (development version)
22

3+
4+
* Make sure that default labels from default mappings doesn't overwrite default
5+
labels from explicit mappings (@thomasp85, #2406)
6+
37
* `stat_count()` now computes width based on the full dataset instead of per
48
group (@thomasp85, #2047)
59

R/plot-construction.r

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -167,8 +167,16 @@ ggplot_add.Layer <- function(object, plot, object_name) {
167167

168168
# Add any new labels
169169
mapping <- make_labels(object$mapping)
170-
default <- make_labels(object$stat$default_aes)
170+
default <- lapply(make_labels(object$stat$default_aes), function(l) {
171+
attr(l, "fallback") <- TRUE
172+
l
173+
})
171174
new_labels <- defaults(mapping, default)
172-
plot$labels <- defaults(plot$labels, new_labels)
175+
current_labels <- plot$labels
176+
current_fallbacks <- vapply(current_labels, function(l) isTRUE(attr(l, "fallback")), logical(1))
177+
plot$labels <- defaults(current_labels[!current_fallbacks], new_labels)
178+
if (any(current_fallbacks)) {
179+
plot$labels <- defaults(plot$labels, current_labels)
180+
}
173181
plot
174182
}

tests/testthat/test-labels.r

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,18 @@ test_that("setting guide labels works", {
5050
)
5151
})
5252

53+
test_that("Labels from default stat mapping are overwritten by default labels", {
54+
p <- ggplot(mpg, aes(displ, hwy)) +
55+
geom_density2d()
56+
57+
expect_equal(p$labels$colour[1], "colour")
58+
expect_true(attr(p$labels$colour, "fallback"))
59+
60+
p <- p + geom_smooth(aes(color = drv))
61+
62+
expect_equal(p$labels$colour, "drv")
63+
})
64+
5365

5466
# Visual tests ------------------------------------------------------------
5567

0 commit comments

Comments
 (0)