[R] Graphics function question
Marc Schwartz
marc_schwartz at comcast.net
Tue Jul 29 19:12:05 CEST 2008
on 07/29/2008 11:38 AM Peter Flom wrote:
> Hello
>
> I have created a graph using the following commands:
>
> <<<
> startBReP3O1T <- diffs$BReP3O1T - diffs$diff_BReP3O1T
> endBReP3O1T <- diffs$BReP3O1T
>
> x <- seq(47,89, length = 10)
> ymin <- min(min(startBReP3O1T), min(endBReP3O1T))
> ymax <- max(max(startBReP3O1T), max(endBReP3O1T))
> y <- seq(ymin, ymax, length = 10)
> plot(x,y, type = 'n', xlab = 'Age', ylab = 'BReP3O1T', main = 'Age, decline and BReP3O1T')
> segments(x0 = startage, x1 = endage, y0 = startBReP3O1T, y1 = endBReP3O1T, col = decline)
> legend('topleft', legend = c('Stable', 'Decline'), lty = 1, col = c(1,2))
>
> I would like to make this into a function. The only thing that changes is BReP3O1T.
> The problem is that sometimes this occurs as text (e.g. in ylab and main) sometimes after a $ (e.g. in the
> first two assigment statements), and sometimes it refers to the values (e.g. in ymin and ymax)
>
> Any help appreciated.
>
> Peter
Hey Peter, LTNS! Job change it looks like from the e-mail address?
Here is one approach. It is not clear from the above, where 'startage',
'endage' and 'decline' come from, so I am passing them as arguments:
In your example above, the function call would be:
MyPlot(diffs$BReP3O1T, diffs$diff_BReP3O1T, startage, endage, decline)
MyPlot <- function(x, y, startage, endage, decline)
{
start <- x - y
end <- x
s1 <- seq(47, 89, length = 10)
# Don't need to use min/max on each vector separately
ymin <- min(start, end, na.rm = TRUE)
ymax <- max(start, end, na.rm = TRUE)
s2 <- seq(ymin, ymax, length = 10)
# Turn 'x' into a label, stripping anything before "$" if present
label <- gsub("^.+\\$", "", deparse(substitute(x)))
plot(s1, s2, type = "n", xlab = "Age", ylab = label,
main = paste("Age, decline and", label)
segments(startage, endage, start, end, col = decline)
legend("topleft", legend = c("Stable", "Decline"), lty = 1,
col = c(1, 2))
}
HTH,
Marc Schwartz
More information about the R-help
mailing list