I'm trying to create a plot with four dynamically positioned lines of expressions. It should look something like the plot below (I've had to do this manually by having each expression on a different line of code and manually setting the x and y coordinates but I want to automate it as I have many plots to do):
All the plots have different scales so it would be good if I could combine the expressions as one object to position in, for example, the top right corner. The code I'm using is as below:
dat <- data.frame("x" = sample(1:100, 800, replace = T),
"y" = sample(1:100, 800, replace = T))
mod <- lm(y ~ poly(x, 1, raw =T), dat)
eq <- linEq(mod, 3)
r2 <- bquote(italic("R")^2~"="~.(round(summary(mod)$adj.r.squared, 2)))
f.value <- round(summary(mod)$fstatistic[[1]], 2)
df1 <- summary(mod)$fstatistic[[2]]
df2 <- summary(mod)$fstatistic[[3]]
f.text <- bquote(italic("F")[.(df1)*","~.(df2)]~"="~.(f.value))
p.value <- bquote(italic("p")~.(ifelse(lmp(mod) < 0.001, "<", "="))~.(ifelse(lmp(mod) < 0.001, "0.001", round(lmp(mod),3))))
p <- ggplot(data=dat, aes(x = x, y = y))+
geom_point()+
geom_smooth(method='lm', formula= y ~ x, se = F)+
xlab("X")+
ylab("Y")+
annotate(geom = "text", x = (1*max(dat$x)), y = (1*max(dat$y)),
label = paste0(eq, r2, f.text, p.value, sep = "\n"),
parse = T,
hjust = "inward")+
theme_classic()
But I get this error:
Error in parse(text = text[[i]]) : :1:18: unexpected symbol 1: y = 51.5 + 0.0278x ^
I know I can use the deparse() function with each singular expression (that's what I did to create the image) but I don't know how to integrate it into my code so that I can position all four lines automatically.
Any ideas would be greatly appreciated!
Many thanks,
Carolina
Some custom functions are needed to make the above code work. They are as below:
linEq <- function(lmObj, dig) {
paste0(c("","y = "),
c("",signif(lmObj$coef[1], dig)),
c("",ifelse(sign(lmObj$coef)[2]==1," + "," - ")),
c("",signif(abs(lmObj$coef[2]), dig)), c("", "x"),
collapse="")
}
lmp <- function (modelobject) {
if (class(modelobject) != "lm") stop("Not an object of class 'lm' ")
f <- summary(modelobject)$fstatistic
p <- pf(f[1],f[2],f[3],lower.tail=F)
attributes(p) <- NULL
return(p)
}


