Skip to content

Possible bug in stage()/after_stat() with scale transformations. #4155

Closed
@teunbrand

Description

@teunbrand

I think I might have found a bug with either the scales or the stage()/after_stat() functions in combination with dates.
I came across this when making a custom stat where I wanted to put default_aes = aes(xmin = after_stat(start), xmax = after_stat(end)) in the ggproto methods, where start and end are computed variables.

What happens is that when I try to apply a stage() or after_stat() to a date variable, it gives me an error that the date transformation is invalid. I don't think it is a problem with stats, as it also shows up with stat_identity().
The attempted plot below is not very interesting, but it is the most minimal example I could come up with.

library(ggplot2)

ggplot(economics) +
  geom_point(aes(x = stage(date, after_stat = x), 
                 y = unemploy))
#> Error: Invalid input: date_trans works with objects of class Date only

The error above doesn't happen for integer or numeric data.

ggplot(economics) +
  geom_point(aes(x = stage(as.integer(date), after_stat = x), 
                 y = unemploy))

And also the error can be rescued by formatting the output as a date again, but this seems overly verbose and seems difficult to anticipate in a custom stat.

ggplot(economics) +
  geom_point(aes(x = stage(date, after_stat = structure(x, class = "Date")), 
                 y = unemploy))

The same is true for other geoms and aesthetics as well. Here are similar examples with after_stat() instead of stage().

ggplot(economics) +
  geom_segment(aes(x = date, xend = after_stat(x + 30),
                   y = unemploy, yend = unemploy))
#> Error: Invalid input: date_trans works with objects of class Date only
ggplot(economics) +
  geom_segment(aes(x = as.integer(date), xend = after_stat(x + 30),
                   y = unemploy, yend = unemploy))

ggplot(economics) +
  geom_segment(aes(x = date, xend = after_stat(structure(x + 30, class = "Date")),
                   y = unemploy, yend = unemploy))

Created on 2020-07-31 by the reprex package (v0.3.0)

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugan unexpected problem or unintended behaviorscales 🐍

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions