Skip to contents

Wrap sentence strings into lines of roughly equal width

Usage

str_wrap_equal(x, max_width = 30L, sep = "\n")

Arguments

x

a character vector

max_width

the maximum number of characters in a line (unless a word is longer than `max_width`)

sep

character string that separates text lines

Value

a character vector

Examples

library(ggplot2)
library(stringr)
library(dplyr)
d <- data.frame(
  Item = c(
    "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
    "Duis pretium arcu quis nibh elementum, sed aliquam enim dignissim.",
    "Nullam et ornare enim, et egestas odio.",
    "Aliquam posuere ante quis magna rutrum, id elementum nulla sodales.",
    "Interdum et malesuada fames ac ante ipsum primis in faucibus.",
    "Aenean rutrum lorem at metus pretium, malesuada porta tellus facilisis.",
    "Vestibulum at convallis enim.",
    "Nam malesuada bibendum rutrum.",
    "Donec risus sapien, pulvinar vitae porttitor non, lobortis ac felis."
  ),
  Proportion = seq(.1,.9,.1)
) |>
  mutate(Item = forcats::fct_inorder(Item))

# Axis labels with stringr::str_wrap
ggplot(d, aes(Proportion, Item)) +
  geom_col() +
  scale_y_discrete(NULL, labels = \(x) str_wrap(x, width = 25L))


# Axis labels with WJSmisc::str_wrap_equal
ggplot(d, aes(Proportion, Item)) +
  geom_col() +
  scale_y_discrete(NULL, labels = \(x) str_wrap_equal(x, max_width = 25L))