Re: [R] Graphics function question

From: Marc Schwartz <marc_schwartz_at_comcast.net>
Date: Tue, 29 Jul 2008 12:12:05 -0500

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



R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Tue 29 Jul 2008 - 17:32:17 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Tue 29 Jul 2008 - 19:32:51 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive