如何在 geom_boxplot 上显示长标题?
我有一个很长的标题,我想将其包含在 ggplot geom_boxplot
的底部。
目前,代码将一行写入标题,但缺少许多预期的标题。我如何将文字包裹在标题中?
我的代码是
p = ggplot(mpg, aes(class, hwy)) + geom_boxplot() +
labs(title="An example title", caption = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.")
我尝试了一些东西,但一无所获,例如 ggplot 主题中的plot.caption。 有人可以帮忙吗?
谢谢。 菲尔,
I have a long caption that I would like to include at the bottom of a ggplot geom_boxplot
.
Currently the code writes a single line to the caption with lots of the intended caption missing. How might I wrap the text in the caption?
My code is
p = ggplot(mpg, aes(class, hwy)) + geom_boxplot() +
labs(title="An example title", caption = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.")
I have experimented with a few things but have got nowhere e.g. plot.caption in the theme of the ggplot.
Could anyone help?
Thank you.
Phil,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
\n
添加到您想要将文本换行的位置(此解决方案中未使用此方法)。但是,由于你的标题很长,很难猜测\n
放在哪里最好,而且不容易对齐结果文本,因此我推荐第二种方法:stringr::str_wrap()
。\n
to the place where you would like to break the text to a new line (this method is not used in this solution). However, since your caption is quite long, it's hard to guess where is the best to put the\n
, and not easy to align the resulting text, therefore I recommend the second method:stringr::str_wrap()
.str_wrap
的另一个选项和替代方案是ggtext::element_textbox
。 ggtext::element_textbox 的一个好处是您不必设置线宽,而是指定教科书的宽度,例如在下面的示例代码中我使用unit(.8 , "npc")
以便标题文本框的长度为绘图宽度的 80%。Another option and alternative to
str_wrap
would beggtext::element_textbox
. A benefit ofggtext::element_textbox
is that you don't have to set the linewidth, instead you specify the width of the textbook, e.g. in my example code below I useunit(.8, "npc")
so that the caption textbox will have a length of 80 percent of the plot width.