Search code examples
rplotglmpredict

glm fitted values mirrored/won't match


I've got a strange problem with plotting the fitted values of a glm.

My code is:

Data <- data.frame("Sp" = c(111.4, 185, 231, 272.5, 309, 342, 371, 399, 
  424, 447, 469, 489, 508, 527, 543, 560, 575, 589, 603, 616, 630, 642, 653,   
  664, 675, 685, 695, 705, 714, 725, 731, 740), "nrC" = 1:32)

modell <- glm(Sp ~ nrC, data = Data, family = Gamma)
pred <- predict(modell, newdata = data.frame("nrC" = 1:32), type = "response")

plot(Data$nrC, Data$Sp, xlim = c(0, 40), ylim = c(50, 1000))
lines(Data$nrC, pred, col = "blue")

The blue line representing the fitted values seems to be ok, apart from being horizontally mirrored.
I'm relatively new to this, so maybe I'm missing something obvious here, but I can't figure out what's wrong.
Doing the same with the data presented here works perfectly fine.

I'be grateful for any hints!


Solution

  • The gamma distribution isn't quite right for this data set. The data shown in the plot as you have it formulated shows a square root-ish looking function. Try specifying the model like this:

    modell <- glm(Sp ~ sqrt(nrC), data = Data, family = gaussian)
    pred <- predict(modell, newdata = data.frame("nrC" = 1:32), type = "response")
    
    plot(Data$nrC, Data$Sp, xlim = c(0, 40), ylim = c(50, 1000))
    lines(Data$nrC, pred, col = "blue")