Emman
Emman

Reputation: 4201

ggplot: How to wrap title text according to margins that are relative to plot's width

When making plots using ggplot2, how can I wrap the title text to fit margins that are relative to the plot's entire width?

library(ggplot2)
library(stringr)

my_title <- c("reltively long sentences that normally isn't appropriate as a title but it is what it is")

ggplot(ToothGrowth, aes(x = factor(dose), y = len)) + 
  geom_boxplot() +
  labs(title = my_title) +
  theme(plot.title = element_text(hjust = 0.5))

plot_1

I'm looking to get something like this

plot_2

Can this be achieved?

Upvotes: 3

Views: 1974

Answers (1)

teunbrand
teunbrand

Reputation: 37923

Not a 100% satisfactory answer to the question but it might still be helpful. Instead of aligning to the entire plot's width, we can align to the panel's width with ggtext::element_textbox(). You can vary the margin argument depending on the size of the title, unit(15, "pt") seemed to work in this particular case.

library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 4.0.2
library(ggtext)
#> Warning: package 'ggtext' was built under R version 4.0.3

my_title <- c("reltively long sentences that normally isn't appropriate as a title but it is what it is")

ggplot(ToothGrowth, aes(x = factor(dose), y = len)) + 
  geom_boxplot() +
  labs(title = my_title) +
  theme(
    plot.title = element_textbox(hjust = 0.5,
                                 width = unit(0.5, "npc"),
                                 margin = margin(b = 15))
  )

Created on 2020-12-25 by the reprex package (v0.3.0)

EDIT: Example with plot.title.position = "plot". If you set element_textbox(..., halign = 0.5), then the distances from the text to the borders is equal, but this will center-align the text.

ggplot(ToothGrowth, aes(x = factor(dose), y = len)) + 
  geom_boxplot() +
  labs(title = my_title) +
  theme(
    plot.title = element_textbox(hjust = 0.5,
                                 width = unit(0.5, "npc"),
                                 margin = margin(b = 15)),
    plot.title.position = "plot"
  )

Created on 2020-12-28 by the reprex package (v0.3.0)

Upvotes: 8

Related Questions