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

社会主义新天地 提交于 2021-02-07 08:55:48

问题


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))

I'm looking to get something like this

Can this be achieved?


回答1:


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)



来源:https://stackoverflow.com/questions/65443331/ggplot-how-to-wrap-title-text-according-to-margins-that-are-relative-to-plots

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!