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

Preserve color() names and use as labels in plot() #27

Merged
merged 6 commits into from Nov 29, 2022

Conversation

gadenbuie
Copy link
Contributor

@gadenbuie gadenbuie commented Nov 29, 2022

This PR does two things:

  1. color() now retains the names of the original vector, if present
  2. plot.colors() uses the color names when label = TRUE, or label can be provided a character vector of color names.

Together, these changes make it easier to use plot() to show off a named color palette.

Take this completely random color palette as an example.

clrs <- c(
  blue = "#447098FF", orange = "#ED6331FF", gray = "#404041FF", 
  teal = "#419498FF", green  = "#72984EFF", burgundy = "#994665FF"
)

When passed to color(), the original color names are retained.

pkgload::load_all()
#> ℹ Loading prismatic
clrs <- color(clrs)
clrs
#> <colors>
#> #447098FF #ED6331FF #404041FF #419498FF #72984EFF #994665FF
names(clrs)
#> [1] "blue"     "orange"   "gray"     "teal"     "green"    "burgundy"

The default plot methods works as previously (labels = FALSE by default)

plot(clrs)

But if labels are requested and if the input vector is named, the names are used for the color labels.

plot(clrs, labels = TRUE)

If the input vector is unnamed, the HEX value of the color is presented (previous behavior).

plot(unname(clrs), labels = TRUE)

Finally, you can also provide labels a character vector equal in length to x if you'd like to use a different label for each color.

plot(clrs, labels = paste("Posit", stringr::str_to_title(names(clrs))))

* if `label = TRUE` and `x` is named, use names for labels
* if `label` is a character vector of length equal to `x`, use those labels
@EmilHvitfeldt
Copy link
Owner

Looking good! Can you add a quick NEWS bullet as well? That would be awesome

You can still use `NA_character_` to get an actual blank label
@EmilHvitfeldt
Copy link
Owner

Thank you!

@EmilHvitfeldt EmilHvitfeldt merged commit d1e0b1b into EmilHvitfeldt:main Nov 29, 2022
@gadenbuie gadenbuie deleted the color-names-labels branch November 30, 2022 14:31
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.

None yet

2 participants