-
Notifications
You must be signed in to change notification settings - Fork 2.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Move guide building to ggplot_build()
#5483
Move guide building to ggplot_build()
#5483
Conversation
Merge branch 'main' into guides_expose_data # Conflicts: # R/guides-.R # tests/testthat/test-guides.R
I've now added the plumbing to make sure that the plot's data reaches the guide building stage where guides interact with layers (at the For this to make slightly more sense, I've added a As a small demonstration that the plumbing works, here is a quick and dirty guide that reports which keys are actually represented in layers. devtools::load_all("~/packages/ggplot2")
#> ℹ Loading ggplot2
orig <- guide_legend()
new <- ggproto(NULL, orig, get_layer_key = function(params, layers, data) {
x <- params$key$.value %in% data[[1]]$colour
print(setNames(x, params$key$.value))
GuideLegend$get_layer_key(params, layers, data = data)
})
p <- ggplot(mtcars, aes(disp, mpg)) +
geom_point(aes(colour = as.factor(cyl))) +
scale_colour_discrete(limits = factor(4:8)) +
guides(colour = new)
b <- ggplot_build(p)
#> 4 5 6 7 8
#> TRUE FALSE TRUE FALSE TRUE Created on 2023-10-24 with reprex v2.0.2 |
ggplot_build()
ggplot_build()
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
LGTM - Heads up @yutannihilation, @clauswilke, @hadley, @karawoo, @paleolimbot - this alters the build order which is generally sacred but we do this for good reasons.
It opens the door for much richer guides together with the guide extension possibilities that @teunbrand has developed
This PR aims to take a step towards #3648.
Briefly, we might want to expose the plot
data
to the guides, so that the guides can observe the data they're supposed to represent. For this to happen, we cannot use the data available inggplot_gtable()
because theafter_scale()
transformations have been applied already and the original data is no longer suitable. Hence, we would need to move guide building to a point beforeafter_scale()
transformations. That last part is what this PR does and it is important to note that it does not do the data exposure (yet).In order to achieve this, the following has to be taken into account:
Guides$draw()
step needs to remain inggplot_gtable()
because it needs access to the theme.Guides
methods need to be independent of the theme.This means that guides don't know about the position or direction of the guide until the
Guide$draw()
step. That has the following implications:More granular details in the comments below: