Home > Software engineering >  In cowplot/add_sub, how to align the multiple text label?
In cowplot/add_sub, how to align the multiple text label?

Time:12-02

In cowplot/add_sub, how do you align a multiple text label? Here is the code below. Thanks!

library(ggplot2)
library(cowplot)
p1 <- ggplot(mtcars,aes(mpg,disp)) 
  geom_line(colour="blue") 
  theme_half_open()

p1_1 <- add_sub(p1,"this is an annotation.\n
                Annotations can span multiple lines.",
                color="red",size=14,
                vpadding = grid::unit(0.5,"lines"),
                lineheight = 0.5,
                x=0.3,y=0.4)
ggdraw(p1_1)

enter image description here

CodePudding user response:

This would get fairly close, though there's an issue with the second line having an extra space before Annotations.

p1_1 <- add_sub(p1,str_replace_all("this is an annotation.\n
              Annotations can span multiple lines.", "\\h ", " "),
                color="red",size=14,
                vpadding = grid::unit(0.5,"lines"),
                lineheight = 0.5,
                x=0,
                y=0.4,
                hjust = 0)

ggdraw(p1_1)

enter image description here

Though, if you are already including the line breaks, then you could just keep the text together.

p1_1 <- add_sub(p1,"this is an annotation.\n\nAnnotations can span multiple lines.",
                color="red",size=14,
                vpadding = grid::unit(0.5,"lines"),
                lineheight = 0.5,
                x=0,
                y=0.4,
                hjust = 0)

ggdraw(p1_1)

enter image description here

  • Related