Package 'stickylabeller'

Title: Sticky Labeller
Description: Create facet labels for ggplot2 using the glue package. Also includes some helpers for sequentially labelling your facets.
Authors: James Goldie [aut, cre]
Maintainer: James Goldie <[email protected]>
License: MIT + file LICENSE
Version: 0.1.0.9100
Built: 2025-02-20 02:43:08 UTC
Source: https://github.com/jimjam-slam/stickylabeller

Help Index


Label facets with a string template.

Description

label_glue returns a labeller function that you can give to the labeller argument of a facet_* function. If you're using label_glue with facet_wrap or you're individually supplying labellers to each variable, you only need one string template. If you're using it with facet_grid directly, you need to give two templates: rows and cols.

Usage

label_glue(rows, cols)

Arguments

rows

A string to be used as the template by glue.

cols

A string to be used as the template by glue.

Details

If you're using the labeller with facet_wrap, you can also use these variables in glue strings:

  • .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.

Value

A labelling function that you can give to the labeller argument of a facet_* function.

Examples

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(
    rows = '{gear} gears',
    cols = '{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})'))