ggplot中使用LateX表达式注释时如何进行换行

10

情况:

我有一个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,但均未成功。

enter image description here

我还尝试了这个label = expression(paste("distribution of ", bar(x), "\n", "under H0")),并在这里查阅过,但仍然没有成功。

问题:

如何将注释(红色文字)拆分为两行?

1个回答

12

您可以使用 atopplotmath 表达式替代(有关详细信息,请参见 ?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()

enter image description here


1
谢谢,这个可行。这种策略能否适用于超过2行的情况呢?(定义p值区域可能会很冗长...) - Sebastian Sauer
太棒了,这非常有帮助。 - Sebastian Sauer

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