R ggplot2 annotate with subscript and tilde

7k views Asked by At

I'm trying to annotate a ggplot2 plot with a label that states the distribution for X1 ~ N(mu=10,sigma=3), where the 1 is meant to be subscript, like this:

label1<-"X[1] ~ N( \U03bc = 10, \U03c3 = 3)"

When I use label1 like this:

library(ggplot2)
label1<-"X[1] ~ N( \U03bc = 10, \U03c3 = 3)"
ggplot() + annotate("text", x=18,y=0.05,label=label1)

The subscript is ignored, the rest is what is wanted.

When I use label1 like this:

library(ggplot2)
label1<-"X[1] ~ N( \U03bc = 10, \U03c3 = 3)"
ggplot() + annotate("text", x=18,y=0.05,label=label1,parse=TRUE)

the subscript is plotted correct, but the tilde transforms in a space.

Any advice how to make and the subscript and the tilde-sign happen? Thanks!

2

There are 2 answers

2
timfaber On

Add % to the tilde as such:

label1<-"X[1] %~% N( \U03bc = 10, \U03c3 = 3)"
0
Z.Lin On

You can replace ~ with %~% in method 2 (i.e. parse = TRUE). I also replaced the unicode for mu & sigma with their greek letter representations:

label1 <- "X[1] %~% N(mu == 10, sigma == 3)"
ggplot() + 
  annotate("text", x=18, y=0.05, label=label1, parse=TRUE)

image