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.
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?
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With