[R] add equation and rsqared to plot

PIKAL Petr petr@p|k@| @end|ng |rom prechez@@cz
Wed Apr 6 21:58:22 CEST 2022

Dear all

I want to add equation and rsquared values to plot and I am lost in correct expression form. I want to have 2 lines, one with equation and one with r squared values.

Here is what I made.

# function to extract values from lm fit.

lm_eqn = function(m) {
  l <- list(a = format(coef(m)[1], digits = 4),
      b = format(abs(coef(m)[2]), digits = 4),
      r2 = format(summary(m)$r.squared, digits = 3),
      r2adj = format(summary(m)$adj.r.squared, digits = 3));
  if (coef(m)[2] >= 0)  {
    eq <- substitute(italic(y) == a + b %.% italic(x), l)
  } else {
    eq <- substitute(italic(y) == a - b %.% italic(x),l)

  req <- substitute(italic(r)^2~"="~r2* ","~~italic(adj.r)^2~"="~r2adj,l)
  expression(atop(eq, req))


x <- 1:10
y <- x*5 +rnorm(10)
fit <- lm(y~x)
text(4,40, lm_eqn(fit))

I know that both eq and req are correct expressions and when the last line in function is either eq or req, the example gives correct result.

But how to get both expressions one above the other is mystery.

Please help.

Best regards.


Osobn� �daje: Informace o zpracov�n� a ochran� osobn�ch �daj� obchodn�ch partner� PRECHEZA a.s. jsou zve�ejn�ny na: https://www.precheza.cz/zasady-ochrany-osobnich-udaju/ | Information about processing and protection of business partner's personal data are available on website: https://www.precheza.cz/en/personal-data-protection-principles/
D�v�rnost: Tento e-mail a jak�koliv k n�mu p�ipojen� dokumenty jsou d�v�rn� a podl�haj� tomuto pr�vn� z�vazn�mu prohl�en� o vylou�en� odpov�dnosti: https://www.precheza.cz/01-dovetek/ | This email and any documents attached to it may be confidential and are subject to the legally binding disclaimer: https://www.precheza.cz/en/01-disclaimer/

	[[alternative HTML version deleted]]

More information about the R-help mailing list