情况:
我有一个 ggplot 图,我想在其中添加一些文本注释。文本注释应出现在两行中(为了可读性和空间),每行包含一些 TeX 公式:
library(tidyverse)
library(latex2exp)
ggplot(NULL, aes(c(-5,5))) +
geom_area(stat = "function", fun = dnorm, fill = "grey40", xlim = c(-2, 2)) +
annotate(geom = "text", label = TeX(paste("Distribution of $\\bar{x}$","\n","under $H_0$")),
x = -1, y = 0.3,
color = "red")
问题:
换行符没有显示。该行没有分成两行。
什么不起作用:
我尝试过paste(TeX(...))
和parse = T
,但没有成功。
我也尝试过这个 label = expression(paste("distribution of ", bar(x), "\n", "under H0"))
查找 here ,没有成功。
问题:
如何将注释(红色文本)分成两行?
最佳答案
您可以使用 atop
和 plotmath
表达式代替(请参阅 ?plotmath
了解更多信息):
ggplot(NULL, aes(c(-5,5))) +
geom_area(stat = "function", fun = dnorm, fill = "grey70", xlim = c(-2, 2)) +
annotate(geom = "text", label = expression(atop("Distribution of"~bar(x), "under"~H[0])),
x = -1, y = 0.3,
color = "red") +
theme_classic()
我更改了此示例的主题和颜色,以便文本脱颖而出。
更新:关于评论,这里有一个选项,尽管您需要调整垂直间距。我们首先构造 exp
,一个 plotmath
表达式列表。然后,在 annotate
中,我们需要 y 是一个长度等于 exp
中元素数量的值向量。 parse=TRUE
告诉 ggplot 将 exp
的元素视为 plotmath
表达式并解析它们:
exp = list("Distribution of"~bar(x),
"under"~H[0],
hat(mu)~"is the mean")
ggplot(NULL, aes(c(-5,5))) +
geom_area(stat = "function", fun = dnorm, fill = "grey70", xlim = c(-2, 2)) +
annotate(geom = "text", label = exp,
x = -1, y = seq(0.32,0.28,length=3),
size=3, color = "red", parse=TRUE) +
theme_classic()
关于r - ggplot 中的换行符用 LateX 表达式进行注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47556473/