Skip to content

Scales with no matching data throw warnings #5909

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

Closed
wants to merge 3 commits into from
Closed
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
@@ -1,5 +1,7 @@
# ggplot2 (development version)

* Scales now throw warnings when no matching data is detected
(@teunbrand, #3743)
* The `arrow.fill` parameter is now applied to more line-based functions:
`geom_path()`, `geom_line()`, `geom_step()` `geom_function()`, line
geometries in `geom_sf()` and `element_line()`.
Expand Down
2 changes: 1 addition & 1 deletion R/plot-build.R
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ ggplot_build.ggplot <- function(plot) {
# Train and map non-position scales and guides
npscales <- scales$non_position_scales()
if (npscales$n() > 0) {
lapply(data, npscales$train_df)
npscales$train_data(data)
plot$guides <- plot$guides$build(npscales, plot$layers, plot$labels, data)
data <- lapply(data, npscales$map_df)
} else {
Expand Down
14 changes: 14 additions & 0 deletions R/scales-.R
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,20 @@ ScalesList <- ggproto("ScalesList", NULL,
lapply(self$scales, function(scale) scale$train_df(df = df))
},

train_data = function(self, data) {
lapply(data, self$train_df)
data_names <- unique0(unlist(lapply(data, colnames)))
for (scale in self$scales) {
if (!any(scale$aesthetics %in% data_names)) {
cli::cli_warn(
"Scale for {.field {scale$aesthetics}} aesthetic{?s} was provided \\
but has no matching data to map.",
call = scale$call
)
}
}
},

map_df = function(self, df) {
if (empty(df) || length(self$scales) == 0) {
return(df)
Expand Down
9 changes: 9 additions & 0 deletions tests/testthat/test-scales.R
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,15 @@ test_that("identity scale preserves input values", {
expect_equal(d1, d2)
})

test_that("a warning is thrown when a scale is not used", {
p <- ggplot(mtcars, aes(disp, mpg)) + geom_point() + scale_colour_discrete()

expect_warning(
ggplot_build(p),
"was provided but has no matching data to map"
)
})

test_that("position scales are updated by all position aesthetics", {
df <- data_frame(x = 1:3, y = 1:3)

Expand Down
Loading