Skip to content

Warn when using constant aesthetics - #5256

Merged
teunbrand merged 4 commits into
tidyverse:mainfrom
teunbrand:warn_constant_aes
Apr 15, 2023
Merged

teunbrand merged 4 commits into
tidyverse:mainfrom
teunbrand:warn_constant_aes

Conversation

@teunbrand

@teunbrand teunbrand commented Apr 1, 2023 •

Copy link
Copy Markdown
Collaborator

This PR aims to fix #5253.

Briefly, it adds a warning when using an all-constant mapping in a layer:

devtools::load_all("~/packages/ggplot2")
#> ℹ Loading ggplot2

p <- ggplot(mtcars, aes(x = 1)) +
  geom_point(aes(y = 2))
b <- ggplot_build(p)
#> Warning: All aesthetics have length 1, but the data has 32 rows in `geom_point()`.
#> ℹ Did you mean to use `annotate()`?

It does take into account inherited aesthetics, so no warning is issued here:

p <- ggplot(mtcars, aes(x = seq_along(mpg))) +
  geom_point(aes(y = 2))
b <- ggplot_build(p)

There is an ambiguous case where I was unsure a warning should be emitted. If a layer inherits an aesthetic that it does not use, should the warning been thrown for the aesthetics it does use?

# To warn or not to warn?
p <- ggplot(mtcars, aes(label = cyl)) +
  geom_point(aes(x = 1, y = 1))
b <- ggplot_build(p)

Created on 2023-04-01 with reprex v2.0.2

The geom_abline()/geom_vline()/geom_hline() are excluded from this check. Extenders can exclude their geoms from this check by using the same exclusion flag (check_constant_aes = FALSE in the geom's ggproto fields).

Comment thread R/layer.R Resolved

@thomasp85 thomasp85 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, but I'd be happy if @clauswilke had a look as well

@clauswilke

Copy link
Copy Markdown
Member

Yes, I think it's fine. Worst case scenario there will be some false positives and we can deal with them then.

@teunbrand
teunbrand merged commit e3b7822 into tidyverse:main Apr 15, 2023
@teunbrand
teunbrand deleted the warn_constant_aes branch April 15, 2023 08:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Surprising behaviour when aes() is used to map all aesthetics to constant values

3 participants