Truncates, trims, and wraps strings. Built for ggplot2 plots with long string labels.

pretty_string(
  x,
  truncate_at = 80,
  truncate_with = "...",
  trim = TRUE,
  wrap_at = 40
)

format_pretty_string(
  truncate_at = 80,
  truncate_with = "...",
  trim = TRUE,
  wrap_at = 40
)

Arguments

x

Strings

truncate_at

Maximum total string length prior to wrapping. Default is 80 characters. Use NULL to skip truncation.

truncate_with

Character string that is added at the end of each string to indicate that the string was truncated. Eats into string length. Default is "..."; set to NULL or "" to skip.

trim

Should whitespace be trimmed? Default is TRUE.

wrap_at

Wraps string at given length, passed to stringr::str_wrap().

Functions

  • format_pretty_string: Provides a pretty string formatter for ggplot2 labels

Examples

text <- "Lorem ipsum dolor sit amet, consectetur adipiscing elit" pretty_string(text, truncate_at = 20, wrap_at = NULL)
#> [1] "Lorem ipsum dolor..."
pretty_string(text, truncate_at = NULL, wrap_at = 10)
#> [1] "Lorem\nipsum\ndolor\nsit amet,\nconsectetur\nadipiscing\nelit"
library(ggplot2) set.seed(654321) ex <- dplyr::data_frame( label = sample(stringr::sentences, 3), value = runif(3, 0, 10) )
#> Warning: `data_frame()` is deprecated, use `tibble()`. #> This warning is displayed once per session.
g <- ggplot(ex) + aes(value, label) + geom_point() g
g + scale_y_discrete( label = format_pretty_string(truncate_at = 25) )
g + scale_y_discrete( label = format_pretty_string(truncate_at = NULL, wrap_at = 20) )