gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 19:35:25 25 4
gpt4 key购买 nike

我正在尝试使用 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 ?

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

如果我尝试单独注释,那么定位很困难,因为 labtxt1的长度和 labtxt2不同的标签/贴纸有所不同。

如何得到想要的结果?

最佳答案

你可以将文本包裹在一个不可见的表格中,

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)

关于r - 在 ggplot2 表达式中混合表达式、纯文本和换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49854480/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com