Search code examples
rggplot2latexline-breaksplotmath

Line break in ggplot annotate with LateX expression


SITUATION:

I have a ggplot diagram, where I want to add some text annotation. The text annotation should appear in two lines (for readibility and space), and each line includes some TeX formula:

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")

PROBLEM:

The line break does not show up. The line is not split in two lines.

WHAT DID NOT WORK:

I have tried paste(TeX(...)), and parse = T, without success.

enter image description here

I also tried this label = expression(paste("distribution of ", bar(x), "\n", "under H0")) looked up here, no success.

QUESTION:

How can I split the annotation (red color text) in two lines?


Solution

  • You could use atop and plotmath expressions instead (see ?plotmath for additional info):

    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()
    

    I've changed the theme and colors for this example so that the text will stand out.

    enter image description here

    UPDATE: Regarding the comment, here's one option, though you'll need to play around with the vertical spacing. We first construct exp, a list of plotmath expressions. Then, in annotate, we need y to be a vector of values equal in length to the number of elements in exp. parse=TRUE tells ggplot to treat the elements of exp as plotmath expressions and parse them:

    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