Insertion of leq symbol in substitute, Mathematical Annotation in R 中

Insertion of leq symbol in substitute, Mathematical Annotation in R

我有下图:

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'

reprex package (v0.3.0)

于 2020-08-22 创建

我想用“小于或等于”替换“<”登录

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

插入字符的最简单方法之一是使用 \u 转义序列。它的使用方式与任何其他转义序列一样,其中 Unicode 字符代码位于 \u 之后。您可以在此处查看示例:

library(ggplot2)

ggplot(mtcars, aes(disp, mpg)) + geom_point() + theme_classic() +
  annotate('text', x=300, y=29, label='Unicode 2264: \u2264') +
  annotate('text', x=300, y=26, label='Unicode 2265: \u2265')

如您所见,小于或等于是Unicode 2264,所以直接在标签中使用\u2264即可。

如果你有

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

那么这些都可以。

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)

中注意到 annotate 不接受表达式。因此 deparse/parse 东西可以消除警告。