r-自动将多项式转换为ggplot2标题中的表达式



以下是我用来自动生成一些回归拟合的一些代码;

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)

此代码应该运行(安装了ggplot2)。问题出现在标有1和2:的行中

  1. 生成多项式的字符串表示
  2. 将字符串设置为绘图标题

目前我的头衔是"6.54*x^0+0.09*x^1+6.54*x^2"。然而,我想要一个更具吸引力的渲染,以便(2)更像是用看到的

 ggtitle(expression(6.54*x^0+0.09*x^1+6.54*x^2)) # (2')

即,提高了幂,减少了乘法等。非常感谢您的帮助!

下面是我为解决问题而构建的一个函数;

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)
}

然后ggtitle(poly_expression(coefs))根据需要进行渲染。