How to create symbol text strings for plots in R

2019-08-10 11:38发布

问题:

I have a plot and would like to add some regression statistics (e.g. F, R2, p) in the plot area. I am familiar with text(), but have been unable to find a comprehensive source of information with examples on how to build text strings with mathematical symbols, sub-and superscripts, etc. Any sources with detailed examples greatly appreciated.

For example, I have a simple linear regression that I would like to extract the stats from and add them to my plot. For example

reg1 <- lm(WW1 ~ PC1, data = WW_Data)

I would like to have something like F1,69 = 14.38, p = < 0.001, R2adj = 0.16 where "1,69" and "adj" is subscript, and "p" is in italics.

EDIT:

Thanks to @Backlin for a great answer to my question. I have expanded on it a bit so that if you get a highly significant p-value the code substitutes "< 0.001" and rounded all the statistics to 2 decimal places, except the p-value which I have rounded to 3.

WW_Data <- data.frame(WW1=rnorm(10), PC1=1:10)
reg1 <- lm(WW1~PC1, WW_Data)
sreg1 <- summary(reg1)
plot(0, 0)
text(0, .2, eval(substitute(
    expression(list(F[list(fn,fd)]==fv,italic(p)==pv,R[adj]^2==R2adj)),
        list(fv = round(sreg1$fstatistic[1],2), fn = sreg1$fstatistic[2],
             fd = sreg1$fstatistic[3], pv = ifelse(sreg1$coefficients["PC1",4] < 0.001, "< 0.001",round(sreg1$coefficients["PC1",4],3)),
             R2adj = round(sreg1$adj.r.squared,2)))))

回答1:

I have struggled a lot with it myself too, but it is actually all in ?plotmath. Your expression would be the following,

# Fixed expression
text(x, y, expression(list(F[list(1,69)]==14.38,italic(p)<0.001,R[adj]^2==0.16)))

# Using the values of your lm
sreg1 <- summary(reg1)
text(x, y, eval(substitute(
    expression(list(F[list(fn,fd)]==fv,italic(p)==pv,R[adj]^2==R2adj)),
        list(fv = sreg1$fstatistic[1], fn = sreg1$fstatistic[2],
             fd = sreg1$fstatistic[3], pv = sreg1$coefficients["PC1",4],
             R2adj = sreg1$adj.r.squared))))

Here's a dummy example of what it looks like.

WW_Data <- data.frame(WW1=rnorm(10), PC1=1:10)
reg1 <- lm(WW1~PC1, WW_Data)
sreg1 <- summary(reg1)
plot(0, 0)
text(0, .2, eval(...)) # The expression above