[R] filling area under a function line

Tom H tom at limepepper.co.uk
Sun May 24 20:32:00 CEST 2009


Hi R collective,

I quite like the "curve" function because you can chuck a R function
into it, and see the graph in one line of R.

I had a google and found some threads for filling under the line;
http://tolstoy.newcastle.edu.au/R/e2/help/07/09/25457.html

However they seem to miss the point of the simplicity of going, "I
wonder what that looks like, and can I have some colour with that
please ;-)" 

So I found the easiest way to do that was to attach a polygon call onto
the end of the curve function definition;

	else plot(x, y, type = type, ylab = ylab, xlim = xlim, log = lg, 

+	polygon(
+			c(from,  x, to), 
+			c(min(y),y,min(y)),
+			col=areacol, lty=0
+	)

}

areacurve(sin(2*pi*6*x+pi/2),areacol="red")

and stick that in my r init file. 

Now the question is, am I missing something elementary here?

Cheers,

T







areacurve<-function (expr, from = NULL, to = NULL, n = 101, add =
FALSE, 
		type = "l", ylab = NULL, log = NULL, xlim = NULL,
areacol="gray", ...) 
{
	sexpr <- substitute(expr)
	if (is.name(sexpr)) {
		fcall <- paste(sexpr, "(x)")
		expr <- parse(text = fcall)
		if (is.null(ylab)) 
			ylab <- fcall
	}
	else {
		if (!(is.call(sexpr) && match("x", all.vars(sexpr), nomatch = 0L))) 
			stop("'expr' must be a function or an expression containing 'x'")
		expr <- sexpr
		if (is.null(ylab)) 
			ylab <- deparse(sexpr)
	}
	if (is.null(xlim)) 
		delayedAssign("lims", {
					pu <- par("usr")[1L:2]
					if (par("xaxs") == "r") 
						pu <- extendrange(pu, f = -1/27)
					if (par("xlog")) 
						10^pu
					else pu
				})
	else lims <- xlim
	if (is.null(from)) 
		from <- lims[1L]
	if (is.null(to)) 
		to <- lims[2L]
	lg <- if (length(log)) 
				log
			else paste(if (add && par("xlog")) 
							"x", if (add && par("ylog")) 
							"y", sep = "")
	if (length(lg) == 0) 
		lg <- ""
	x <- if (lg != "" && "x" %in% strsplit(lg, NULL)[[1L]]) {
				if (any(c(from, to) <= 0)) 
					stop("'from' and 'to' must be > 0 with log=\"x\"")
				exp(seq.int(log(from), log(to), length.out = n))
			}
			else seq.int(from, to, length.out = n)
	y <- eval(expr, envir = list(x = x), enclos = parent.frame())


	if (add) {
		lines(x, y, type = type, ...)
	}
	else plot(x, y, type = type, ylab = ylab, xlim = xlim, log = lg, 
				...)

	polygon(
			c(from,  x, to), 
			c(min(y),y,min(y)),
			col=areacol, lty=0
	)
	
}




More information about the R-help mailing list