tidyverse / ggplot2

An implementation of the Grammar of Graphics in R
https://ggplot2.tidyverse.org
Other
6.39k stars 2k forks source link

Feature request: non-rectangular panel clipping #5951

Open teunbrand opened 2 weeks ago

teunbrand commented 2 weeks ago

Currently, turning clip = "on" has little effect for coord_radial() with out-of-bounds values. In the example below, I'd like it to be possible to clip points to the pacman-shape and not display any data in the upper quarter of the plot.

library(ggplot2)

ggplot(mpg, aes(displ, hwy)) +
  geom_point() +
  scale_x_continuous(limits = c(3, 6), oob = scales::oob_keep) +
  coord_radial(
    start = 0.25 * pi, end = 1.75 * pi, 
    clip = "on"
  )

Created on 2024-06-20 with reprex v2.1.0

Clipping currently is a property of the grob added to the gtable, and thus the clipping is enforced by a rectangular gtable cell. While the clipping is setup by the coord, it ultimately under controlled by the facets, e.g. here:

https://github.com/tidyverse/ggplot2/blob/ba0b18ab7bcc37e86b971e382710ce2cac6ed60e/R/facet-null.R#L66

The coord currently has no option to intervene in the clipping, which would ideally occur before panels are handed off to the Facet$draw_panels() method. I think the best option will be to move the responsibility of the following piece of code from the Layout to the Coord, which can then intervene as it sees fit.

https://github.com/tidyverse/ggplot2/blob/ba0b18ab7bcc37e86b971e382710ce2cac6ed60e/R/layout.R#L79-L96