Skip to content
Prev 85760 / 398503 Next

srt --- slope text with function?

Thank you, Duncan.  This led me to the info I needed.  Here is a
simple utility function that does what I needed---maybe it will come
in helpful for others.

################################################################
#### native.slope computes a suitable srt from a function around
#### a point on a function.  This is useful until text() gets
#### an srt parameter that is relative to the coordinate system.
####   (Ideally, R would be able to slope along a function.)
################################################################

native.slope <- function( x, y, where.i,
			 xlim = par()$xaxp, ylim= par()$yaxp,
			 asp.ratio = (par()$fin)[1]/(par()$fin)[2] ) {
  if (where.i<=1) { return(0); }
  if (where.i>=length(y)) { return(0); }
  if (length(x)!=length(y)) {
    stop("native.slope: Sorry, but x and y must have equal dimensions,
not ", length(x), " and ", length(y), "\n"); }

  # native slope in a 1:1 coordinate system
  d= ( (y[where.i-1]-y[where.i+1])/(x[where.i-1]-x[where.i+1]) );
  if (is.na(d)) return(0); # we do not know how to handle an undefined
spot at a function!

  d.m= (ylim[2]-ylim[1])/(xlim[2]-xlim[1]); # now adjust by the axis scale
  if (is.na(d)) stop("native.slope: internal error, I do not have
sensible axis dimensions (", xlim, ylim, ")\n");

  if (is.na(asp.ratio)) stop("native.slope: internal error, I do not
have a reasonable drawing aspect ratio");

  net.slope= d/asp.ratio/d.m;
  return(slope = atan(net.slope)/pi*180.0 )
}


# some test code
x<- seq(-10,20,by=0.1)
y<- x*x;

plot( x, y, type="l" );

display= ((1:length(y))%%40 == 0)

for (i in 1:(length(y))) {
  if (display[i]) {
    points(x[i],y[i], pch=19);
    srt= native.slope( x, y, i );
    text( x[i], y[i], paste(i,"=",x[i],"=",srt), srt=srt, cex=0.9 );
  }
}
On 2/4/06, Duncan Murdoch <murdoch at stats.uwo.ca> wrote: