1

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:

  1. Generates a string representation of the polynomial
  2. 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!

Filburt
  • 17,626
  • 12
  • 64
  • 115
Joe
  • 1,455
  • 2
  • 19
  • 36
  • Something as depicted here ? http://stackoverflow.com/questions/7549694/ggplot2-adding-regression-line-equation-and-r2-on-graph –  Jul 02 '15 at 10:38
  • Yes! I will try and modify that case for the more general polynomial. Thx – Joe Jul 02 '15 at 10:40
  • Single line fixed it - replace (2) with `ggtitle(parse(text=eq))`. Could not adapt the other solution because substitute work lexically and it was giving me problems with the arrays. – Joe Jul 02 '15 at 10:52

1 Answers1

1

Here's a function that I built to solve my problem;

poly_expression <- function(coefs){

  # build the string
  eq <- paste0(round(coefs,2),'*x^', (1:length(coefs)-1), collapse='+')

  # some cleaning
  eq <- gsub('\\+\\-','-', eq) # +-n -> -n
  eq <- gsub('\\*x\\^0','', eq) # n*x^0 <- n
  eq <- gsub('x\\^1','x', eq) # n*x^1 <- nx

  eq <- parse(text=eq) # return expressions

  return(eq)
}

Then ggtitle(poly_expression(coefs)) renders as required.

Joe
  • 1,455
  • 2
  • 19
  • 36