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

4

我正在尝试使用ggplot2创建一些标签/贴纸。 我从一个来源中提取标签的文本并尝试进行绘制。我可以按照以下方式完成:

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)

enter image description here

如何将labtxt1中的文本改为粗体,同时保留labtxt2中的普通文本,保持对齐和linewidth

我尝试使用带有\nexpression,但这会破坏对齐方式,使用atop则会破坏linewidth

如果我单独进行注释,则对于不同的标签/贴纸,labtxt1labtxt2的长度不同,因此位置设置很困难。

如何获得所需的结果?


你看过这个https://dev59.com/7VwZ5IYBdhLWcg3wWfGl吗? - amobox
1个回答

2
您可以将文本包装在一个不可见的表格中,
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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接