Here is some code I am using to auto generate some regression fits;
require(ggplot2)
# Prep data
nPts = 200
prepared=runif(nPts,0,10)
rich=5-((prepared-5)^2)/5 + 5*runif(length(prepared))
df <- data.frame(rich=rich, prepared=prepared)
deg = 1 # User variable
lm <- lm(df$rich ~ poly(df$prepared, deg, raw=T))
# Create expression
coefs <- lm$coefficients
eq <- paste0(round(coefs,2),'*x^', 0:length(coefs), collapse='+') # (1)
pl <- ggplot(df, aes(x=prepared, y=rich)) +
geom_point() +
geom_smooth(method = "lm", formula = y ~ poly(x,deg), size = 1) +
ggtitle(eq) # (2)
print(pl)
This code should run (with ggplot2 installed). The problem is in the lines marked 1 and 2:
- Generates a string representation of the polynomial
- Sets the string as the plot title
As it stand my title is "6.54*x^0+0.09*x^1+6.54*x^2"
. However I want a more attractive rendering so that (2) is more like would be seen with:
ggtitle(expression(6.54*x^0+0.09*x^1+6.54*x^2)) # (2')
i.e, powers raised, multiplications dropped etc. Any help much appreciated!