Search code examples
rplotmodellattice

How to print R^2 for each panel in xyplot


In case I am plotting a series of regression models.

xyplot(
  Petal.Width  ~ Petal.Length | Species,
  data = iris,
  panel = function(x, y, ...) {
    panel.xyplot(x, y, ...)
    
    mod1 <- lm(y~x)
    panel.abline(mod1, col='#0080ff')
    
    mod2 <- lm(y~poly(x, 2))
    panel.curve(predict(mod2, newdata=data.frame(x=x)), col='#ff8000', lwd=2)
    
    mod3 <- lm(y~poly(x, 3))
    panel.curve(predict(mod3, newdata=data.frame(x=x)), col='#ff00ff', lwd=2)
  },
  grid = TRUE
)

How could I add beside each curve the related R squared? Thanks


Solution

  • You can do this with panel.text() inside your panel function.

    library(lattice)
    xyplot(
      Petal.Width  ~ Petal.Length | Species,
      data = iris,
      panel = function(x, y, groups, ...) {
        panel.xyplot(x, y, ...)
        mod1 <- lm(y~x)
        mod2 <- lm(y~poly(x, 2))
        mod3 <- lm(y~poly(x, 3))
        panel.abline(mod1, col='#0080ff')
        panel.curve(predict(mod2, newdata=data.frame(x=x)), col='#ff8000', lwd=2)
        panel.curve(predict(mod3, newdata=data.frame(x=x)), col='#ff00ff', lwd=2)
        
        r21 <- sprintf("Rsq = %.2f", summary(mod1)$r.squared)
        r22 <- sprintf("Rsq = %.2f", summary(mod2)$r.squared)
        r23 <- sprintf("Rsq = %.2f", summary(mod3)$r.squared)
        panel.text(1, 2.5, r21, adj=c(0,.5), col='#0080ff')
        panel.text(1, 2.35, r22, adj=c(0,.5), col='#ff8000')
        panel.text(1, 2.2, r23, adj=c(0,.5), col='#ff00ff')
      },
      grid = TRUE
    )
    

    Created on 2024-04-04 with reprex v2.0.2