tidyverse / ggplot2

An implementation of the Grammar of Graphics in R

Home Page:https://ggplot2.tidyverse.org

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Feature request: non-rectangular panel clipping

teunbrand opened this issue · comments

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:

grob_clip <- c("off", "off", "off", "off", coord$clip, "off", "off", "off", "off")

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.

ggplot2/R/layout.R

Lines 79 to 96 in ba0b18a

# Draw individual panels, then assemble into gtable
panels <- lapply(seq_along(panels[[1]]), function(i) {
panel <- lapply(panels, `[[`, i)
panel <- c(facet_bg[i], panel, facet_fg[i])
coord_fg <- self$coord$render_fg(self$panel_params[[i]], theme)
coord_bg <- self$coord$render_bg(self$panel_params[[i]], theme)
if (isTRUE(theme$panel.ontop)) {
panel <- c(panel, list(coord_bg), list(coord_fg))
} else {
panel <- c(list(coord_bg), panel, list(coord_fg))
}
ggname(
paste("panel", i, sep = "-"),
gTree(children = inject(gList(!!!panel)))
)
})