Reputation: 4201
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))
Can this be achieved?
Upvotes: 3
Views: 1974
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