############################################################################ # R ROUTINE FOR PLOTTING ONE-DIMENSIONAL FUNCTIONS # # (by Jeffrey S. Rosenthal, probability.ca, 2007) # # The statistical software R includes various plotting routines like # "plot" and "curve", which usually work well but sometimes fail # [e.g. for the constant function "f = function(x) return(5)"]. # So, I provide here a simpler function-plotting routine, which only # works for one-dimensional functions, and which runs slowly, but # which does always(?) work as expected. (Released under GPL.) ############################################################################ plotfunction = function(ff, from=xlim[1], to=xlim[2], col="black", add=FALSE, xlim=c(0,1), numpoints=1000 ) { xlist = ylist = NULL; ymin = +Inf; ymax = -Inf; for (i in 1:numpoints) { xval = from + (to-from) * i / numpoints; yval = ff(xval); xlist = c(xlist, xval); ylist = c(ylist, yval); if (yval < ymin) ymin = yval; if (yval > ymax) ymax = yval; } if (add==FALSE) { plot( c((from+to)/2, (ymin+ymax)/2), type='n', xlim=c(from,to), ylim=c(ymin,ymax), xlab="x", ylab=paste( deparse(substitute(ff)), "(x)", sep="" ) ); } lines(xlist, ylist, col=col); }