Wrap text labels across multiple lines on a ggplot2 figure.
Source:R/text_wrapper.R
text_wrapper.RdThis function returns a ggplot with the text labels split on to new lines based on a given length of characters.
Usage
text_wrapper(
plot,
title_wrap = 40,
axis_title_wrap = 30,
axis_wrap = 20,
other_wrap = 30,
spaces = TRUE
)Arguments
- plot
A ggplot2 figure (S3: gg, ggplot).
- title_wrap
The maximum number of characters before a new line in the plot title and subtitle. Defaults to 40.
- axis_title_wrap
The maximum number of characters before a new line in the plot axis titles. Defaults to 30.
- axis_wrap
The maximum number of characters before a new line in the plot axis tick labels. Defaults to 20.
- other_wrap
The maximum number of characters before a new line in the other text labels on the plot like the title of legends for fill, color, size etc. Defaults to 30.
- spaces
Whether to replace underscores with spaces in all text labels. Defaults to
TRUE.
Details
This function returns a ggplot with the text labels (e.g. title and
axis tick labels) split on to new lines based on a given length of characters.
Also, replaces as.type() style function calls like as.factor() or
as.numeric(as.character()) in x-axis, y-axis and various legend titles
like fill, color, size etc. automatically. Can also replace underscores.
with spaces in all text labels.
Examples
library(ggplot2)
library(scales)
library(stringr)
## generate a plot
## if you want to use a numeric variable as discrete use `as.factor()` when setting `fill`
cars_plot <- ggplot(data = mtcars, aes(x = cyl, y = as.numeric(mpg), fill = as.factor(cyl))) +
geom_bar(stat="identity") +
exploristics_theme()
library(magrittr)
## pipe along with the colour scheme
cars_plot_final <- cars_plot %>%
exploristics_fill(colour_pal="Expl_RGB") %>%
text_wrapper()