Search code examples
rtextggplot2linear-regressionsubscript

subscript in ggplot text


I have encountered problem in putting subscript in plot Text. First I did simple linear normal regression of 2 continuous variable and plotted it using ggplot.

Olm=lm(LPBEO ~ SNTO, LPBESNTR)
Ointercept=signif(coef(Olm)[1], digits=3)
Oslope=signif(coef(Olm)[2], digits=3)
Otext= paste("O-LPBE[50]","=",Ointercept,"+ (", Oslope, "x O-SN[50])")
Opred<- predict(Olm, interval="prediction")
Odataframe=data.frame(cbind(LPBESNTR$SNTO,LPBESNTR$LPBEO,Opred))
colnames(Odataframe)=c("SNTO", "LPBEO", "fit", "lwr", "upr")
O=ggplot(Odataframe, aes(x=SNTO, y=LPBEO))+
  geom_point(shape=20,colour = "red", size = 3)+
  geom_line(aes(y=lwr), color = "red", linetype = 2, size=1)+
  geom_line(aes(y=upr), color = "red", linetype = 2, size=1)+
  geom_smooth(method=lm, fill = "orange",colour="red", size = 1 )+
  ggtitle("SNT O vs LPBE O") + 
  theme(plot.title = element_text(face="bold",size=20)) + 
  xlab(bquote(~"Log"[10]~ "SN"[50]))+ 
  theme(axis.title.x = element_text(face='bold', size=20),axis.text.x = element_text(face='bold', size=20)) +
  ylab(bquote(~"Log"[10]~"LPBE"[50]))+
  theme(axis.title.y = element_text(face='bold', size=20),axis.text.y  = element_text(face='bold', size=20)) + 
  annotate("text", x = 1.5, y = 4.5, label = Otext, color="black", fontface="bold", size = 5, parse=FALSE)
O

I want to add subscript in text for display of regression equation. For that first I created a object Otext using paste command, which I used for annotating plot. the command creates object but not able to display subscripts in texts. I am not able to point out where is the issue in code.
I need 50 to appear as subscript in text annotation to the plot,

Otext= paste("O-LPBE[50]","=",Ointercept,"+ (", Oslope, "x O-SN[50])")

however it shows as such in brackets not as subscripts.

I request someone to clarify how to do this. Thank you


Solution

  • You can use expression() for the subscripts but because you want to reference a variable as well we need to use bquote():

    Otext=bquote(paste("O-LPBE"[50],"=",.(Ointercept),"+ (", .(Oslope), " x O-SN"[50],")"))
    

    Here we use .(variable) to reference your variables and [subscript] for the subscripts (^ for superscripts).