r - ggplot 中的换行符用 LateX 表达式进行注释

标签 r ggplot2 latex line-breaks plotmath

情况:

我有一个 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")) 查找 here ,没有成功。

问题:

如何将注释(红色文本)分成两行?

最佳答案

您可以使用 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()

我更改了此示例的主题和颜色,以便文本脱颖而出。

enter image description here

更新:关于评论,这里有一个选项,尽管您需要调整垂直间距。我们首先构造 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

关于r - ggplot 中的换行符用 LateX 表达式进行注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47556473/

相关文章:

r - 如何正确从 .csv 创建 XML?

python - ggplot2 不存在于 python 的 rpy2 中?

r - 来自 dismo::gmap() 和 ggplot2 的谷歌地图

r - 用ggplot2将多个y值绘制为单独的线的正确方法

c - 使用 pdflatex 在 C 代码中编译 LaTeX 文件

git - Git 中的文件级别跟踪(来自同一目录中多个分支的文件)

r - 使用移动平均或内核平滑对二进制变量进行平滑

python - 在 conda 环境中在 MacOS 上导入 R 库时如何解释和修复 'shared object not found' 错误?

r - 将 purrr::walk2() 应用于管道末端的 data.frames 的 data.frame

python - 如何从 python 中检查计算机上是否安装了 LaTeX 和 TeX Live?