Skip to content

Should alpha() support patterned fills? #367

Closed

Description

@teunbrand

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)
  )

Activity

  1. thomasp85 commented on Nov 1, 2023

    @thomasp85
    Member

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

  2. teunbrand commented on Nov 1, 2023

    @teunbrand
    CollaboratorAuthor

    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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions