在 ggplot2 表达式中混合表达式、纯文本和换行符

Mixing expression, plain text and newline in ggplot2 expression

我正在尝试使用 ggplot2 创建一些 labels/stickers。 我正在从源中提取标签的文本并尝试绘制。我可以这样做:

labtxt1 <- c("This text should be bold", "This text should also be bold", "Another text to be bold")
labtxt1 <- strwrap(labtxt1, width = 20)

labtxt2 <- c("This text should not be bold", "This text should also not be bold", "Another text to be plain")
labtxt2 <- strwrap(labtxt2, width = 20)

library(ggplot2)
library(Hmisc)

labtxt <- c(labtxt1, labtxt2)
labtxt <- paste(labtxt, collapse = "\n", sep = "")
labtxt <- escapeRegex(labtxt)

ggplot(x=1, y = 1) + 
  annotate("text", x = 0.5, y = 0.5, 
           label = labtxt,
           colour = "red", parse = F, lineheight = 0.8)

现在如何使 labtxt1 中的文本与 labtxt2 中的文本一起变为粗体并保持对齐 linewidth

我试过用 expression\n,这会弄乱理由,还有 atop,但会弄乱线宽。

如果我尝试单独注释,那么定位会很困难,因为 labtxt1labtxt2 的长度因 labels/stickers 的不同而不同。

如何得到想要的结果?

您可以将文本包裹在不可见的 table,

library(ggplot2)
library(gridExtra)

label <- "plain text\nbold('bold line')\nitalic('italic line')\nplain again"
disect <- strsplit(label, "\n")[[1]]

mytheme <- ttheme_minimal(core = list(fg_params = list(parse=TRUE, col="red",
                                                       hjust=0, x=0.1)))
tg <- tableGrob(as.matrix(disect), theme=mytheme)

ggplot(x=1, y = 1) + 
  annotation_custom(tg)