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

Classed palettes with properties #427

Open
wants to merge 10 commits into
base: main
Choose a base branch
from

Conversation

teunbrand
Copy link
Contributor

This PR aims to fix #426.

Briefly, it introduces two classes of palettes: <pal_continuous> and <pal_discrete>, which I mostly see as making {scales}' palettes more formal.

The classes are simply functions with attributes that provide information about the palette.
The <pal_discrete> class accepts a scalar n as input and spits out a vector of n distinct values.
The <pal_continuous> class accepts a numeric vector between (0, 1) and spits out a vector of equal length.
All existing palettes have been given appropriate classes.

The palette_type() function probes the type attribute, indicating what palettes can be used for, like "colour" or "linetype".
The palette_na_safe() function probes <pal_continuous> on whether NA are translated (e.g. in using the colour_ramp(na.colour) argument).
The palette_nlevels() function probes <pal_discrete> what the maximum n is.

The as_continuous_pal() function can cast <pal_discrete> to <pal_continuous>. For colour types, this is wrapping the discrete palette in colour_ramp().
The as_discrete_pal() function can cast <pal_continuous> to <pal_discrete>. This is mostly palette_fun(seq(0, 1, length.out = n).

A small demo:

devtools::load_all("~/packages/scales")
#> ℹ Loading scales

# Probing properties
pal <- pal_brewer("qual")
is_discrete_pal(pal)
#> [1] TRUE
palette_nlevels(pal)
#> [1] 8

# Converting from continuous to discrete
pal <- pal_gradient_n(rainbow(10))
is_continuous_pal(pal)
#> [1] TRUE
disc <- as_discrete_pal(pal)
is_discrete_pal(disc)
#> [1] TRUE
show_col(disc(9))

Created on 2024-04-16 with reprex v2.1.0

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

Successfully merging this pull request may close these issues.

Feature request: properties for palettes
1 participant