R 图中标注公式

R 图中标注公式

plot 函数的图

theta <- seq(-pi,pi,by=0.05)
y <- sin(theta)
plot(theta,y,type='l',col='red')
eq <- expression(y == sin(theta))
text(x=-1, y=0.8, labels=eq, cex=1.5, col='blue')

注:

  • expression()中的下标为[],上标为^,空格为~,连接符为*
  • expression()常与 paste()联合使用。如eq <- expression(paste(y == sin(theta),'的图形'))
  • 也可用bquote函数
  • 公式表1
  • 公式表2

ggplot2绘图

ggplot2 绘图可以使用下述语句标注文字或公式

p<-ggplot(data,aes(x=,y=))

p + geom_text(aes(x=10,y=5,label=""))
或
p + geom_label(aes(x=10,y=5,label=""),parse=TRUE)
或
p + annotate("text",x=10,y=5,label="",parse=TRUE)

标注公式

公式中如果有希腊字母,需要先用substitute函数,参数parse设置为TRUE,即parse = TRUE。ggplot2中的label对象必须是字符,即label的形式一般是label = as.character(as.expression(eq)))

data("faithful")
library(ggplot2)
p <- ggplot(faithful,aes(x=eruptions,y=waiting)) + 
  geom_point() + 
  stat_smooth(method='lm',formula = y~x,colour='red')

model.lm<-lm(formula = waiting ~ eruptions, data = faithful)
#summary(model.lm)
#对于一元线性回归方程y=ax+b,Intercept是指的截距,x对应的是系数。

l <- list(a = as.numeric(format(coef(model.lm)[1], digits = 4)),
          b = as.numeric(format(coef(model.lm)[2], digits = 4)),
          r2 = format(summary(model.lm)$r.squared, digits = 4),
          p = format(summary(model.lm)$coefficients[2,4], digits = 4))

eq <- substitute(italic(y) == a + b %.% italic(x)~","~italic(R)^2~"="~r2~","~italic(P)~"="~p, l)

p +   
  labs(title = as.expression(eq)) +
  geom_text(aes(x = 4, y = 50, label = as.character(as.expression(eq))),parse = TRUE)
library(ggplot2)
library(patchwork)
set.seed(566)
x1<-arima.sim(n=200,model=list(ar=-0.9))
x1d<-data.frame(Time=c(time(x1)),TimeSeries=c(x1))
eq<-substitute(AR(1) *'序列'*':'*~ phi[1]==-0.9)
p1<-ggplot(x1d,aes(x=Time,y=TimeSeries)) + 
           geom_line() +
           geom_point(color='red') + 
           annotate("text",x=100,y=5,color='blue',parse = TRUE,
           label=as.character(as.expression(eq)))

x1acf<-acf(x1,lag.max=38,plot=F)
names(x1acf)[c(1,4)]<-c('ACF','Lag')
x1fd<-with(x1acf,data.frame(Lag,ACF))
p1acf<-ggplot(x1fd, mapping=aes(x=Lag,y=ACF)) + 
       geom_segment(mapping = aes(xend=Lag,yend=0)) +
       geom_hline(aes(yintercept=0.05),linetype=2,color='darkblue') +
       geom_hline(aes(yintercept=-0.05),linetype=2,color='darkblue') + 
       geom_text(aes(x=20,y=0.9,
       label=as.character(as.expression("ACF:phi[1]==-0.9"))),parse = TRUE)

p1+p1acf
posted @ 2022-03-13 15:21  hzworld  阅读(280)  评论(0编辑  收藏  举报