label_glue | R Documentation |
Returns a labeller function that you can give to the labeller
argument of
a facet_*
function.
label_glue(row_template, col_template, summary_data = NULL, ...)
row_template |
A string to be used as the template by
|
col_template |
A string to be used as the template by
|
summary_data |
A data frame of additional variables to reference in the templates. Must also include the facet grouping variables. |
... |
Other arguments to be passed to |
If you're using label_glue()
with ggplot2::facet_wrap()
or you're
individually supplying labellers to each variable, you only need one string
template: row_template
.
If you're using it with ggplot2::facet_grid()
, you need to supply two
templates: one for the rows (row_template
) and one for the columns
(col_template
).
If you're using the labeller with ggplot2::facet_wrap()
, you can also
use these variables in the templates:
.n
to add numbers to each facet;
.l
or .L
to add lower- or uppercase letters
.r
or .R
to add lower- or uppercase roman numerals.
A labelling function that you can give to the labeller
argument
of the facetting function.
library(ggplot2)
library(stickylabeller)
# wrap facet columns in braces to refer to their values in the labels
p1 <- ggplot(iris, aes(x = Sepal.Length, y = Petal.Length)) + geom_point()
p1 + facet_wrap(
~ Species,
labeller = label_glue("Sepal and petal lengths in {Species} plants"))
# distinguish panels with .n (numbers), .l (lowercase), .L (uppercase),
# .r or .R (lower- or uppercase roman) if you're using facet_wrap
p1 + facet_wrap(
~ Species,
labeller = label_glue("({.n}) {Species}"))
# you can also use label_glue with facet_grid
p2 <- ggplot(mtcars, aes(x = disp, y = mpg)) + geom_point()
p2 + facet_grid(
gear ~ cyl,
labeller = label_glue(
row_template = "{gear} gears",
col_template = "{cyl} cylinders"))
# you can add summary statistics in a couple of ways. the easiest (in terms
# of plot code) is to join a summary back into the original data and to add
# the new columns in the facet spec
library(dplyr)
cyl_stats <- mtcars %>%
group_by(cyl) %>%
summarise(cyl_n = n(), cyl_meanmpg = sprintf("%#.2f", mean(mpg)))
mtcars_joined <- mtcars %>% inner_join(cyl_stats)
p3 <- ggplot(mtcars_joined, aes(x = disp, y = mpg)) + geom_point()
p3 + facet_wrap(
~ cyl + cyl_n + cyl_meanmpg,
labeller = label_glue(
"({.l}) {cyl} cylinders\n(n = {cyl_n}, mean = {cyl_meanmpg})"))
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.