1

I am trying to create a custom caption to fit under my plot such that a portion of the caption text should be bold and the other part plain. At the same time, I would like the caption to wrap so that the caption is not truncated.

cap <- expression(paste('\"', bold("This text should be bold"), ' This text should not be bold, but should be plain? And everything should fit under the plot\"'))

Here is my first attempt. As one can see, the bold text appears correctly; however, the caption text is truncated at the plot border on the right.

ggplot(data = mtcars, mapping = aes(x=wt, y=mpg))+
  theme(plot.caption = element_text(hjust = 0, size = 14))+
  labs(caption = cap)

enter image description here

In the second attempt, I used stringr::str_wrap so that the text is no longer truncated; however, the expression is not evaluated and so the caption is incorrect.


ggplot(data = mtcars, mapping = aes(x=wt, y=mpg))+
  theme(plot.caption = element_text(hjust = 0, size = 14))+
  labs(caption = str_wrap(cap))


enter image description here

Does anyone know how to reconcile this problem? That is, I would like the caption to both evaluate so that it appears correctly, and also wrap.

Thanks so much.

HumanityFirst
  • 305
  • 1
  • 8

1 Answers1

2

expression can't render linebreaks. You can get two lines with the atop function, but the relatively new ggtext package is much more flexible. For example:

library(ggplot2)
library(ggtext)

cap2 <- "<b>This text should be bold.</b> This text should not be bold, but should be plain? And everything should fit under the plot"

ggplot(data = mtcars, mapping = aes(x=wt, y=mpg)) +
  labs(caption = cap2) +
  theme(plot.caption=element_textbox_simple(hjust=0, size=14))

enter image description here

eipi10
  • 91,525
  • 24
  • 209
  • 285