Apply a function to each label and character/factor variable in the plot object.
Source:R/zulugg.R
gg_apply.Rd
Applies the string function fun
to each label present in the plot
object p
, as well as to any character or factor variables in the
underlying data. The function, fun
, should accept and return character
vectors. It can either be a simple prettifying function or it can perform
more complex lookup to replace variable names with variable labels. If
variables are factors, they are converted to character before applying the
function after which they are reconverted to factor. Care is taken to
preserve the factor ordering.
Arguments
- p
A
ggplot2
object- fun
A function to be applied to the labels in
p
- ...
Other variables to be passed to
fun
- .labs
logical or character, indicating whether to apply the function to the labels in p. If TRUE, apply to all character or factor variables in
p
. IfFALSE
,NULL
or empty vector, do not apply the function to any variables. If a character vector containing the names of variables, apply the function to those particular variables. An error may be thrown if the vector refers to non-existing labels. Defaults toTRUE
.- .vars
logical or character. If
TRUE
, apply to all character or factor variables in p. IfFALSE
,NULL
or empty vector, do not apply the function to any variables. If a character vector containing the names of variables, apply the function to those particular variables. An error may be thrown if the vector refers to non-existing variables or variables that are neither characters nor factors. Defaults toTRUE
.
See also
Other functions extending ggplot
:
gg_apply_labs()
,
gg_integer_breaks()
Examples
# This uses snakecase::to_sentence_case to prettify the labels
# Note: The plot is assigned to a named variable before piping to gg_apply_labs()
# This is to avoid issues due to the precedence of operators,
# (%>% has higher precedence than +)
library(dplyr, warn.conflicts=FALSE)
library(ggplot2)
library(forcats)
library(snakecase)
p <- starwars %>%
filter(mass < 1000) %>%
mutate(species = species %>% fct_infreq %>% fct_lump(5) %>% fct_explicit_na) %>%
ggplot(aes(height, mass, color=species, size=birth_year)) +
geom_point()
#> Warning: There was 1 warning in `mutate()`.
#> ℹ In argument: `species = species %>% fct_infreq %>% fct_lump(5) %>%
#> fct_explicit_na`.
#> Caused by warning:
#> ! `fct_explicit_na()` was deprecated in forcats 1.0.0.
#> ℹ Please use `fct_na_value_to_level()` instead.
p %>% gg_apply(snakecase::to_sentence_case)
#> Warning: Removed 23 rows containing missing values (`geom_point()`).