【问题标题】:Line break in ggplot annotate with LateX expressionggplot 中的换行符使用 LateX 表达式进行注释
【发布时间】:2018-05-13 09:07:00
【问题描述】:

情况:

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

问题:

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

【问题讨论】:

    标签: r ggplot2 latex line-breaks plotmath


    【解决方案1】:

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

    【讨论】:

    • 谢谢,这行得通。这种策略是否也适用于 >2 行? (定义 p 值区域可以很冗长...)
    • 太好了,很有帮助
    猜你喜欢
    • 2021-02-20
    • 2018-11-13
    • 2014-12-08
    • 1970-01-01
    • 1970-01-01
    • 2017-11-16
    • 2012-05-18
    • 2021-08-03
    • 2018-07-24
    相关资源
    最近更新 更多