Skip to content
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

Should alpha() support patterned fills? #367

Closed
teunbrand opened this issue Oct 30, 2022 · 2 comments
Closed

Should alpha() support patterned fills? #367

teunbrand opened this issue Oct 30, 2022 · 2 comments

Comments

@teunbrand
Copy link
Contributor

teunbrand commented Oct 30, 2022

Since R 4.2.0, the {grid} package has supported vectorised patterns. A simplified example from the link, with a list of patterns, is the code below:

library(grid)

grad <- linearGradient(
  c(palette()[2], "white"), 
  y1 = 0.5, y2 = 0.5, group = FALSE
)
pat  <- pattern(
  circleGrob(r = unit(2, "mm"), gp = gpar(col = 2, fill = 2)),
  width = unit(5, "mm"), height = unit(5, "mm"),
  extend = "repeat", group = FALSE
)

grid.rect(1:2/3, width=1/4, height=1/2,
          gp=gpar(fill=list(grad, pat)))

Created on 2022-10-30 by the reprex package (v2.0.1)

Let's say we might want to try to adopt this in ggplot2, like so:

library(ggplot2)

ggplot(data.frame(x = 1:2), aes(x, x)) +
  geom_tile(aes(fill = factor(x)), width = 1) +
  scale_fill_manual(
    values = list(grad, pat)
  )
#> Error in `geom_tile()`:
#> ! Problem while converting geom to grob.
#> ℹ Error occurred in the 1st layer.
#> Caused by error:
#> ! Unknown colour name: list(x1 = 0, y1 = 0.5, x2 = 1, y2 = 0.5, stops = c(0, 1), colours = c("#DF536B", "white"), extend = "pad", group = FALSE)

As can be seen above, we currently can't use this in ggplot2. I think the only thing currently prohibiting this is the alpha() function that can't handle a list of patterns as input.

If I change the alpha() function to be like this (real solution should probably be more elegant):

alpha <- function(colour, alpha = NA) {
  
  if (is.list(colour)) {
    return(colour)
  }
  
  ... # rest of function body
}

And build the package and re-load ggplot2 (which doesn't lend itself well to reprexes), I can get exactly what I might have expected:

library(ggplot2)

ggplot(data.frame(x = 1:2), aes(x, x)) +
  geom_tile(aes(fill = factor(x)), width = 1) +
  scale_fill_manual(
    values = list(grad, pat)
  )

@thomasp85
Copy link
Member

Is this still needed in your current ggplot2 PR for pattern fills?

@teunbrand
Copy link
Contributor Author

No, this issue should be fixed by tidyverse/ggplot2#5299

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants