Search code examples
rggplot2substitutionmathematical-expressions

Insertion of leq symbol in substitute, Mathematical Annotation in R


I have the following graph:

library(tidyverse)

mm<-70
sdm<-12
weight_lim<-c(30, 110)
xrange<-55
ggplot(data = data.frame(weight = weight_lim), aes(weight)) +
  stat_function(fun = dnorm, n = 101, args = list(mean = mm, sd = sdm),color=1) +
  ylab("f(weight)") + scale_x_continuous(breaks=seq(weight_lim[1],weight_lim[2], by=5)) + 
  stat_function(fun = dnorm, args = list(mean = mm,sd=sdm),
                xlim = c(weight_lim[1],xrange[1]),
                geom = "area",fill="red",alpha=0.5)+
  annotate("text", x = 40, y = .02, 
           label = substitute(paste("P(X < ",v," ) = ",s),list(v=format(xrange, nsmall = 1),s=round(pnorm(xrange,mm,sdm),4))),
           size=3 , fontface="bold")+
  theme_bw()
#> Warning in is.na(x): is.na() applied to non-(list or vector) of type 'language'

Created on 2020-08-22 by the reprex package (v0.3.0)

I would like to replace “<” by "less than or equal to" sign in

substitute(paste("P(X < ",v," ) = ",s),list(v=format(xrange, nsmall = 1),s=round(dnorm(xrange,mm,sdm),4)))


Solution

  • If you have

    vv = format(xrange, nsmall = 1)
    ss = round(dnorm(xrange,mm,sdm),4)
    

    Then either of these will work.

    lab = bquote(P(X <= .(vv)) == .(ss)) 
    # or
    lab = substitute(P(X <= v) == s, list(v=vv, s=ss))
    
    p + annotate("text", x = 40, y = .02, label = deparse(lab), parse=TRUE)
    

    Noting from annotate a formula (with bqoute or substitute) in R (ggplot) gives Error that annotate doesn't take expressions., hence the deparse/parse stuff to get rid of the warnings.