在 ggplot2 中使用 geom_text() 时,如何在标签中合并斜体字母和换行符?

问题描述 投票:0回答:1

我希望创建一个 geom_tile 图,它总结了我一直在使用的特定模型的输出。具体来说,在每个图块中,我想在新行上显示 beta 系数和 p 值。不过我想使用斜体“p”,即 p = 0.05

下面是我想要实现的目标,除了我想使用斜体“p”

df = data.frame(x = letters[1:10],y = letters[11:20], value = c(1:10),p = c((1:10)/10))


ggplot(df, aes(x = x, y = y)) +
  geom_tile() +
  geom_text(mapping = aes(label = paste(value, "\n",'p', "=", p)), parse = F, color = "white")

但是,当我设置 parse = T 并使用 expression() 时,我遇到了问题

我已经尝试过了

ggplot(df, aes(x = x, y = y)) +
  geom_tile() +
  geom_text(mapping = aes(label = paste(value,"/n",expression(italic("p")), "==", p)), parse = T, color = "white")

这仅输出“值”,而不是新行上的“p = ..”

如果我尝试不使用新行,

ggplot(df, aes(x = x, y = y)) +
  geom_tile() +
  geom_text(mapping = aes(label = paste(value,expression(italic("p")), "==", p)), parse = T, color = "white")

我收到以下错误:

geom_text()
中的错误: !将 geom 转换为 grob 时出现问题。 ℹ 第二层发生错误。 由
parse()
中的错误引起: ! :1:3:意外的符号 1:1斜体 ^

有解决办法吗?

ggplot2 newline geom-text plotmath italics
1个回答
0
投票

如果使用其他包适合您,那么

ggtext::geom_richtext
可以轻松实现您想要的结果,因为它允许通过 HTML、CSS 或 Markdown 设置文本或单个单词的样式。为此,将要斜体化的文本包裹在
*
(斜体的 Markdown 语法)中,并使用 html 标签
<br>
添加新行。此外,由于
geom_richtext
类似于
geom_label
,我们必须将
fill
颜色以及标签框轮廓颜色(又名
label.color
)设置为
NA

df <- data.frame(x = letters[1:10], y = letters[11:20], value = c(1:10), p = c((1:10) / 10))

library(ggplot2)
library(ggtext)

ggplot(df, aes(x = x, y = y)) +
  geom_tile() +
  ggtext::geom_richtext(
    aes(label = paste(value, "<br>", "*p*", "=", p)),
    color = "white",
    fill = NA,
    label.color = NA
  )

© www.soinside.com 2019 - 2024. All rights reserved.