Skip to content

Annotate a segmented linear regression plot

2 messages · Ben Harrison, David Winsemius

#
On 28 September 2012 16:38, David Winsemius <dwinsemius at comcast.net> wrote:
Thank you. I was stupid to ask such a trivial question along with a
not-so-trivial one. The second part of the question was probably more
important: is there a way to obtain the location of segments produced
by the segmented package, so that I can annotate them easily?

I have since asked this question of Vito, the package's author. Here
is his response:

#####
dear Ben,
here a possible solution,

o is the segmented fit

  r<-o$rangeZ[,1]
  est.psi<-o$psi[,2]
  v<-sort(c(r, est.psi))
  xCoord<-rowMeans(cbind(v[-length(v)], v[-1]))

  Z<-o$model[,o$nameUV$Z]

  id<-sapply(xCoord, function(x)which.min(abs(x-Z)))
  yCoord<-broken.line(o)[id]

  plot(o, col=2:4, res=T)
  text(xCoord, yCoord, labels=formatC(slope(o)[[1]][,1], digits=2),
pos=4, cex=1.3)

Play with pos, cex and digits to modify the appearance of the labels.

vito
#####
I hope this is better.

Ben.
#
On Oct 2, 2012, at 3:38 PM, Ben Harrison wrote:

            
I guess it depends on what you mean by "the location of segments". It's easy enough to retrun the x-values for the knots:

    o$psi[ , "Est."]

I do not see a `predicted.segmented` function, so might need to construct separate lm.predict estimates for values between the pairs of x-values if you meant you wanted the y-values for the knots.