automatically convert polynomial to expression in ggplot2 title

喜欢而已 提交于 2021-02-10 15:40:43

问题


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!


回答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.



来源:https://stackoverflow.com/questions/31182226/automatically-convert-polynomial-to-expression-in-ggplot2-title

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!