ggplot:如何根据与绘图宽度相关的边距包装标题文本
使用 制作绘图时ggplot2,如何包装标题文本以适应相对于绘图整个宽度的边距?
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))
我想得到这样的东西
这能实现吗?
回答
这个问题的答案不是 100% 令人满意,但它可能仍然有帮助。我们可以使用 与面板的宽度对齐,而不是与整个绘图的宽度对齐ggtext::element_textbox()。您可以margin根据标题的大小改变参数,unit(15, "pt")似乎在这种特殊情况下有效。
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))
)
由reprex 包(v0.3.0)于 2020 年 12 月 25 日创建
编辑:示例与plot.title.position = "plot". 如果设置element_textbox(..., halign = 0.5),则文本到边框的距离相等,但这将使文本居中对齐。
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"
)
由reprex 包(v0.3.0)于 2020 年 12 月 28 日创建