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

Recycle colors in a palette when exceeding the maximum number of defined colors #373

Closed
MikkoVihtakari opened this issue Dec 5, 2022 · 1 comment

Comments

@MikkoVihtakari
Copy link

Is there an easy way of changing the default behavior of scales palette functions to repeat colors when running out of defined alternatives instead of returning NAs? I am looking for something similar to grDevides::palette.colors(..., recycle = TRUE). This would come in handy when passing manual colors to ggplot2 as there are more predefined palettes in the scales package than in grDevices.

library(scales)

## Works in grDevices

grDevices::palette.colors(20, palette = "Set 1", recycle = TRUE)
#>  [1] "#E41A1C" "#377EB8" "#4DAF4A" "#984EA3" "#FF7F00" "#FFFF33" "#A65628"
#>  [8] "#F781BF" "#999999" "#E41A1C" "#377EB8" "#4DAF4A" "#984EA3" "#FF7F00"
#> [15] "#FFFF33" "#A65628" "#F781BF" "#999999" "#E41A1C" "#377EB8"

## My clumsy approach for scales palettes
color_palette <- scales::brewer_pal(palette = "Set1")

color_palette(5)
#> [1] "#E41A1C" "#377EB8" "#4DAF4A" "#984EA3" "#FF7F00"
color_palette(20)
#> Warning in RColorBrewer::brewer.pal(n, pal): n too large, allowed maximum for palette Set1 is 9
#> Returning the palette you asked for with that many colors
#>  [1] "#E41A1C" "#377EB8" "#4DAF4A" "#984EA3" "#FF7F00" "#FFFF33" "#A65628"
#>  [8] "#F781BF" "#999999" NA        NA        NA        NA        NA       
#> [15] NA        NA        NA        NA        NA        NA

repeat_palette <- function(n, pal = color_palette) {
  if(inherits(
      tryCatch(pal(n), error=function(e) e, warning=function(w) w),
    "character")
    ) {
    pal(n)
  } else {
    tmp <- suppressWarnings(pal(1e5))
    tmp <- tmp[!is.na(tmp)]
    rep(tmp, length.out = n)
  }
}

repeat_palette(20)
#>  [1] "#E41A1C" "#377EB8" "#4DAF4A" "#984EA3" "#FF7F00" "#FFFF33" "#A65628"
#>  [8] "#F781BF" "#999999" "#E41A1C" "#377EB8" "#4DAF4A" "#984EA3" "#FF7F00"
#> [15] "#FFFF33" "#A65628" "#F781BF" "#999999" "#E41A1C" "#377EB8"
repeat_palette(5)
#> [1] "#E41A1C" "#377EB8" "#4DAF4A" "#984EA3" "#FF7F00"

scales::show_col(repeat_palette(20))

Created on 2022-12-05 with reprex v2.0.2

@thomasp85
Copy link
Member

This is not planned. In general the palette behaviour is made intentional so as to ensure that the input data works with the palette

@thomasp85 thomasp85 closed this as not planned Won't fix, can't repro, duplicate, stale Nov 1, 2023
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