“\n” command not working to make 2 or 3-line long figure caption using textGrob

我的未来我决定 提交于 2019-12-22 00:04:25

问题


I have been trying to make a 2 to 3-line figure caption below the combined plots using the following script:

library(grid)
library(gridExtra)
library(ggplot2)

g1 <- ggplotGrob(pl) #pl is my plot 1
g2 <- ggplotGrob(pl1) #pl1 is my plot 2

g <- rbind(g1, g2) #this combines my two plots
caption <- textGrob(expression(paste(bold("Figure 1"), ". This is the first line with a", italic( " scientific name."),"\nThis should be the second line.","\nThis is the third line.")), hjust=0, x=0) #caption to be incorporated at the lower left of the combined plots
g <- gtable::gtable_add_rows(g, unit(2,"mm") + grobHeight(caption), -1) #incorporating the combined plots with the caption
g <- gtable::gtable_add_grob(g, caption, nrow(g), l = 4, r = ncol(g)) #incorporating the combined plots with the caption
grid.newpage()
grid.draw(g)

But when I tried to execute this command, it still forms a one-liner caption.

UPDATE:

Thank you Sir @baptiste for your suggestions. Now I know that newline command is incompatible with plotmath. However, when I tried to incorporate the new script, my plots disappeared and did not combine with the caption.

Now my query is:

  • How am I going to incorporate the script suggested by Sir @baptiste to my original script (as shown above), and combine the two plots (pl and pl1) with the caption (provided by Sir @baptiste) at the lower left portion of the combined plots?

Any suggestions on how I can fix this? Thank you very much.


回答1:


plotmath is incompatible with newline characters, unfortunately. I'd suggest filling a table with the text split into separate lines,

library(gridExtra)
library(grid)

table_label <- function(label, params=list())  {

  params <- modifyList(list(hjust=0, x=0), params)

  mytheme <- ttheme_minimal(core = list(fg_params = params), parse=TRUE)
  disect <- strsplit(label, "\\n")[[1]]
  m <- as.matrix(disect)
  tableGrob(m, theme=mytheme)

}

txt <- 'bold("Figure 1")\nThis is another line.\n alpha~beta*" are greek letters"'
grid.newpage()

g <- table_label(txt)
grid.draw(g)



来源:https://stackoverflow.com/questions/36001047/n-command-not-working-to-make-2-or-3-line-long-figure-caption-using-textgrob

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