Skip to content

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

Closed

Description

@aphalo

When all mappings in a geom are to constant values, whole-plot default data should not affect the number of grobs generated.
Current behaviour of making as many copies as rows there are in data is surprising/counterintuitive as demonstrated by https://stackoverflow.com/questions/75881173/

In the example below, there is no mapping to variables in data in layer 2 of either p1 or p2, however, when rendered, p1 includes as many grobs for layer 2, as there are rows in data. In p2 only one grob is created, resulting in a much smaller SVG file.

library(ggplot2)

p1 <- ggplot(data = mpg, aes(class, hwy)) + 
  geom_boxplot() + 
  geom_text(aes(label = "***", x = 5.5, y = 41), size = 6)

str(p1$layers[[2]]$data)
#>  list()
#>  - attr(*, "class")= chr "waiver"
str(p1$layers[[2]]$mapping)
#> List of 3
#>  $ x    : num 5.5
#>  $ y    : num 41
#>  $ label: chr "***"
#>  - attr(*, "class")= chr "uneval"

p2 <- ggplot(data = mpg, aes(class, hwy)) + 
  geom_boxplot() + 
  geom_text(data = data.frame(), aes(label = "***", x = 5.5, y = 41), size = 6)

str(p2$layers[[2]]$data)
#> 'data.frame':    0 obs. of  0 variables
str(p1$layers[[2]]$mapping)
#> List of 3
#>  $ x    : num 5.5
#>  $ y    : num 41
#>  $ label: chr "***"
#>  - attr(*, "class")= chr "uneval"

object.size(cowplot::as_grob(p1))
#> 814272 bytes
object.size(cowplot::as_grob(p2))
#> 794984 bytes

svglite::svglite("p1.svg")
print(p1)
dev.off()
#> png 
#>   2

file.size("p1.svg")
#> [1] 50646

svglite::svglite("p2.svg")
print(p2)
dev.off()
#> png 
#>   2

file.size("p2.svg")
#> [1] 12667

# the diference can be seen starting at line 94 in the .svg files.

The following line appears once in p2.svg, and repeated 234 times in p1.svg.

<text x='515.78' y='82.03' text-anchor='middle' style='font-size: 17.07px; font-family: "Arial";' textLength='19.92px' lengthAdjust='spacingAndGlyphs'>***</text>

Created on 2023-03-30 with reprex v2.0.2

Activity

  1. smouksassi commented on Mar 30, 2023

    @smouksassi

    adding visually a way to see what is going on

    library(ggplot2)
    library(patchwork)
     ggplot(data = mpg, aes(class, hwy)) + 
      geom_boxplot() + 
      geom_text(aes(label = "***", x = 5.5, y = 41), size = 6)+
      geom_point(aes( x = 5.5, y = 35), size = 10, alpha=0.2,color="red",
                 position = position_jitter())+
      geom_point(data=data.frame(),
                 aes( x = 5.5, y = 30), size = 10, alpha=0.2,color="red",
                 position = position_jitter())+
      geom_point(x=5.5,y=25, size = 10, alpha=0.2,color="red")+ #position error
      geom_point(data=data.frame(x = 5.5, y = 20),
                  aes(x=x,y=y ), size = 10, alpha=0.2,color="red",
                  position = position_jitter())

    Created on 2023-03-30 with reprex v2.0.2

  2. teunbrand commented on Mar 30, 2023

    @teunbrand
    Collaborator

    There is already the annotate() function to solve this, as explained by the the FAQ here: https://ggplot2.tidyverse.org/articles/faq-annotation.html. Is the suggestion here to auto-detect such cases?

  3. aphalo commented on Mar 30, 2023

    @aphalo
    ContributorAuthor

    Yes, this is a suggestion to detect such cases and either handle them elegantly or trigger an error. There are multiple ways of getting around this, including the use of annotate() but on the other hand this bug/feature(?) can slow down rendering and badly bloat the size of PDF and SVG files (in my example above for SVG by a factor of 4). Doing this silently seems like a bad idea to me, even if documented. I think this may have become a problem only when the behaviour of aes() was changed so that it accepts mappings to constant values. In the early (how early?) implementations of aes() it was possible to use it only to map variables in data, and mappings to constant values were allowed only outside aes() as named arguments to geometries. Somewhere along the road, this changed.

  4. teunbrand commented on Mar 30, 2023

    @teunbrand
    Collaborator

    I'm on the fence on handling them elegantly, as I'm uncertain whether that would break some plots out there. Throwing an error would be problematic for geom_vline()/geom_hline()/geom_abline() that already do automatic simplification internally. A warning might be appropriate, but it would get pretty hairy because the aforementioned geoms need to be absolved from the check.

  5. aphalo commented on Mar 30, 2023

    @aphalo
    ContributorAuthor

    It would not be the first time that plots at the edge of the rules have been broken by 'ggplot2' updates. I do not think this is good, but almost every single 'dplyr' update breaks some code. That data that is not mapped to any aesthetics affects the output of a geom is in my view inconsistent with the grammar of graphics. Non expert and casual users cannot be expected to know or remember this as a special case to be aware of. I, as an old-time user, tend to avoid using aes() to map constant values, but once this has been allowed, the behaviour must remain, I think, within the expectations/logic of the grammar, and if not, the unexpected behaviour should be easily noticed by users. On the other hand, I do agree with you that this may not be an easy to solve problem because of default mappings defined in geom definitions. I am not suggesting changing the defintions of geoms, but I hope somewhere in the guts of 'ggplot2' code there is a possibility to check if all mappings are to constant values, and these values are being added as columns to default data, and at least issue a message or warning in such a case. I think that if the test is done late enough, geom_vline(), geom_hline() and geom_abline() would not need to be treated as special cases, because they define a local data object early on in the case when they behave like annotations. A message or warning issued when the plot is rendered, would still be very useful. Anyway, making it possible to use any geom with all aesthetics mapped to constant values is what may have been a bad decision, but reverting this feature is no longer an option, I think.

  6. clauswilke commented on Mar 30, 2023

    @clauswilke
    Member

    @aphalo Just to be clear: This is not new behavior. It's been this way for as long as I can remember, so probably at least a decade. Also, setting all aesthetics in a geom to a constant value without providing an empty data frame is an unidiomatic use of the grammar, though I understand that people are routinely confused about this. (Look at all the bug reports about incorrectly applied alpha. They are nearly all actually due to the problem here: duplication of a geometric element.)

    Honestly, I'm not sure this can be caught in a check, because the geom doesn't know if all aesthetics are constant, certainly not if you don't set inherit.aes = FALSE (another option that almost nobody knows about or uses correctly). It may just be one of these pitfalls that we have to educate people about over and over.

  7. teunbrand commented on Mar 30, 2023

    @teunbrand
    Collaborator

    I'm probably too new at this to remember such behaviour. But indeed, as Claus points out, the following can be quite ambiguous because label gets propagated to the point layer:

    library(ggplot2)
    
    p <- ggplot(mpg, aes(displ, hwy, label = cyl)) +
      geom_point(aes(x = 1, y = 1))
      
    # Note: multiple unique values despite constant aesthetics in layer mapping
    unique(layer_data(p))
    #>   x y label PANEL group shape colour size fill alpha stroke
    #> 1 1 1     4     1    -1    19  black  1.5   NA    NA    0.5
    #> 2 1 1     6     1    -1    19  black  1.5   NA    NA    0.5
    #> 3 1 1     8     1    -1    19  black  1.5   NA    NA    0.5
    #> 4 1 1     5     1    -1    19  black  1.5   NA    NA    0.5

    Created on 2023-03-31 by the reprex package (v2.0.0)

    However, I think it would be possible to catch many, but not all, cases where annotate() would be more appropriate with a check.

  8. aphalo commented on Mar 31, 2023

    @aphalo
    ContributorAuthor

    @clauswilke Yes, I know that this is not new behaviour. And this is not a major bug that would need to be fixed in a rush. I only realized yesterday while answering a question at Stackoverflow how confusing this can be to some users. You also mention confusion caused around alpha. The question is that many users of R and 'ggplot2' have little or no background in programing and do not use R every day or even every week. For example, I teach R to biology students and advice them on the data analysis for their theses.

    I greatly appreciate the effort that has been put in recent updates to 'ggplot2' in making error messages more informative, as this can greatly improve users' experience. Adding a message or warning for the problem we are dealing with in this issue would be an additional improvement in the same direction.

  9. clauswilke commented on Mar 31, 2023

    @clauswilke
    Member

    I think realistically the only way to do this is in the geom, at draw time, the geom could check whether any data is duplicated. This would have to be implemented separately for each geom, and it could potentially be quite slow for geoms that frequently handle large datasets (such as points).

  10. thomasp85 commented on Mar 31, 2023

    @thomasp85
    Member

    Yeah, I agree with @clauswilke. I fully empathise with the intent of the issue but I realistically can't see how this could be done without majorly impacting everyone else on performance. @teunbrand you are of course welcome to attempt a PR if you can see a way out of it

  11. aphalo commented on Apr 1, 2023

    @aphalo
    ContributorAuthor

    @thomasp85 I agree that there is a compromise involved between avoiding the performace cost for those caught by this problem and the possible overall performance hit to those who know how to avoid the problem in their code. My guess is, however, that anything that bloats the plot-rendering task is likely to have higher impact on performance than tests done on the data and mapping. However, you know the code internals in detail, and I don't. Let's see if @teunbrand can create a PR. I will also let you know if I can come up with some idea on how a test could be implemented.

  12. clauswilke commented on Apr 1, 2023

    @clauswilke
    Member

    As an example, for a scatter plot with 100,000 points, this operation alone would add 0.3 seconds to the plot time (on my machine, which is a decent Macbook Pro). This is a penalty that would affect every single plot produced by ggplot2, without any benefit for the majority of users (IMO).

    library(tidyverse)
    
    n <- 100000
    df <- tibble(a = rnorm(n), b = rnorm(n), c = rnorm(n), d = rnorm(n),
                 e = letters[sample(1:26, n, TRUE)], f = letters[sample(1:26, n, TRUE)],
                 g = letters[sample(1:26, n, TRUE)])
    
    bench::mark(unique(df))
    #> Warning: Some expressions had a GC in every iteration; so filtering is disabled.
    #> # A tibble: 1 × 6
    #>   expression      min   median `itr/sec` mem_alloc `gc/sec`
    #>   <bch:expr> <bch:tm> <bch:tm>     <dbl> <bch:byt>    <dbl>
    #> 1 unique(df)    301ms    397ms      2.52    8.38MB     16.4

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

  13. clauswilke commented on Apr 1, 2023

    @clauswilke
    Member

    And then there's the possibility of false positives, when a dataset does actually have duplicated points ggplot would then potentially start complaining about those.

  14. teunbrand commented on Apr 1, 2023

    @teunbrand
    Collaborator

    My thought wasn't to check for actual duplicates, but to check for constants in the mapping of a layer. If you feed aes() a constant, it will be a vector of length 1, whereas if you feed it a non-constant, it will be a quosure of length 2.

    library(ggplot2)
    map <- aes(x = 1:10, y = 2)
    lengths(map)
    #> x y 
    #> 2 1
    lapply(map, class)
    #> $x
    #> [1] "quosure" "formula"
    #> 
    #> $y
    #> [1] "numeric"

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

    You can then skip the expensive check as mentioned by Claus because you're only testing the shape of the aesthetics, not the actual data. Of course this doesn't catch cases where a <- 4; aes(x = 1, y = a), because a will be captured as quosure, but I'd say it might be an improvement overall.

  15. teunbrand commented on Apr 1, 2023

    @teunbrand
    Collaborator

    Or, you could check for constants after evaluation of aesthetics, but before recycling rules have been applied, in i.e. ggplot2:::check_aesthetics(). This would also get rid of the edge case mentioned above.

  16. clauswilke commented on Apr 1, 2023

    @clauswilke
    Member

    @teunbrand Can you make this work for inherited aesthetics? Because in general people will not turn off inheriting of aesthetics so you have to check the complete final expression.

  17. teunbrand commented on Apr 3, 2023

    @teunbrand
    Collaborator

    Yeah we can. For implementation details, let's discuss over at #5256.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions