-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Closed as not planned
Description
The following code works, producing output with xmin and xmax aligned to bins:
ggplot(mtcars, aes(mpg, hp)) +
geom_rect(aes(xmin = mpg - 5, xmax = mpg + 5, ymin = hp - 5, ymax = hp + 5)) +
scale_x_binned(breaks = seq(0,60, 10))But this code, which ought to do the same thing, produces an empty plot:
ggplot(mtcars, aes(mpg, hp)) +
geom_tile(aes(x = mpg, y = hp, height = 10, width = 10)) +
scale_x_binned(breaks = seq(0,60, 10))The underlying reason is in the second call to layout$map_position() in ggplot_build().
- There, the binned scale tries to remap
xvariables back from a factor to (the binned version of) their original values. ForGeomRectwhich hasxmaxandxminfrom the start, this works. - But
GeomTilecalculatesxminandxmaxfromxandwidth. By the time it gets tolayer$compute_geom_1,xhas been transformed to a "factor"-style numeric of bins. The geom doesn't realise this and happily adds the original width to the bin. - Then the second call to
layout$map_position()takes this wonky data and turns it back, typically toNA. - Finally when the geom displays, the NA values for
xminandxmaxare removed.
In other words, GeomTile$setup_data() is being called after the first map_position(), but in this case at least, it needs to be called before it.
This bug exists in ggplot2 3.4.2, and also on github main as of today.
Syutenjyo