12666727b9
12666727b9

Reputation: 1139

How to add hyperbolic curve in lattice

Let's pretend I want to add an hyperbolic curve to this plot

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

Even though, such function won't fit data, the curve should be like the one you see in the picture. Could you please suggest to me the proper code?

Upvotes: 1

Views: 96

Answers (1)

SamR
SamR

Reputation: 20494

You can add the various components as a function provided to the panel parameter of xyplot().

In this case we can use:

  1. panel.xyplot() to plot the points.
  2. panel.lines() for the horizontal line at the mean.
  3. panel.text() for the label saying "mean".
  4. panel.curve() for the hyperbolic function. As you've said it doesn't fit the data I've just eyeballed a function that looks similar. You can change this by editing the fun and line_scale parameters.
xyplot(
    dist ~ speed,
    cars,
    panel = function(x, y, fun = sinh, line_scale = 5, text_scale = 1.2, from = 0, to = 25, ...) {
        panel.xyplot(x, y, col = "black")
        panel.lines(x = seq(from, to), y = mean(x), col = "red", lwd = 2)
        panel.text(min(x) * text_scale, mean(x) * text_scale, "mean", col = "red")
        panel.curve(
            fun(x / line_scale),
            from = from,
            to = to,
            type = "l",
            col = "blue",
            lwd = 3
        )
    }
)

enter image description here

All these functions and their parameters are set it out in the lattice panel functions docs.

Upvotes: 2

Related Questions