12666727b9
12666727b9

Reputation: 1139

How to add hyperbolic/exponential curve in lattice graph via model function

Let's take as example the following data

data(cars)    
xyplot(dist ~ speed, cars)

I would like to add an exponential/hyperbolic function, as the code here below does,

but using the model function related to exponential/hyperbolic function. To make it clearer, I know that several model can be plotted thanks to the panel.abline()of lattice package, by adding the following option to xyplot. Do you know, how I can do the same - drawing the hyperbolic curve via explicit model function between dist and speed variables - like the lm() in panel.abline() do?

  panel.abline(lm(dist ~ speed, data = cars), col.line = "red")
         panel.abline(lm(dist ~ I(speed^2), data = cars), col.line = "green")
         panel.abline(lm(dist ~ I(speed^3), data = cars), col.line = "blue")
         panel.superpose(x, y, ..., type = c("p", "r"), pch = 16, lty = 1:3, lwd = 2)
         panel.curve(
           fun(x/ line_scale),
           from = from,
           to = to,
           type = "l",
           col = "blue",
           lwd = 3
         )
       }

thanks

Upvotes: 3

Views: 34

Answers (1)

DaveArmstrong
DaveArmstrong

Reputation: 22034

You can do it with panel.lines() and generate predictions from a model that has the transformation in it, then unwind the transformation (if it's on the dependent variable). Here's an example, if I understand what you're asking:

library(lattice)
data(cars)    
xyplot(dist ~ speed, cars, panel = function(x,y){
  panel.lines(x, exp(predict(lm(log(y) ~ x), newdata= data.frame(speed=x))), col.line="red")
  panel.points(x,y, col="gray50")
})

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

Upvotes: 3

Related Questions