Advertisement
mgordon

New version of termplot

Jan 29th, 2012
3,541
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 10.93 KB | None | 0 0
  1. termplot2 <- function (model, data = NULL, envir = environment(formula(model)),
  2.         partial.resid = FALSE, rug = FALSE, terms = NULL, se = FALSE,
  3.         xlabs = NULL, ylabs = NULL, main = NULL, col.term = 2, lwd.term = 1.5,
  4.         col.se = "orange", lty.se = 2, lwd.se = 1, col.res = "gray",
  5.         cex = 1, pch = par("pch"), col.smth = "darkred", lty.smth = 2,
  6.         span.smth = 2/3, ask = dev.interactive() && nb.fig < n.tms,
  7.         use.factor.levels = TRUE, smooth = NULL, ylim = "common",
  8.         rug.type = "rug", yscale="regular",
  9.         col.dens="#80808033", se.type="line", density.proportion = .1, log="",
  10.         ...)
  11. {
  12.     # Options for new variables
  13.     # rug.type: "rug", "density"
  14.     # yscale: "regular", "exponential"
  15.     # se.type: "line", "polygon"
  16.    
  17.     # Basic functions used by termplot
  18.     se.lines <- function(x, iy, i, ff = 2) {
  19.         tt <- ff * terms$se.fit[iy, i]
  20.         upper_ci <- tms[iy, i] + tt
  21.         lower_ci <- tms[iy, i] - tt
  22.        
  23.         if (identical(yscale, "exponential")){
  24.             upper_ci <- exp(upper_ci)
  25.             lower_ci <- exp(lower_ci)
  26.         }
  27.         lines(x, upper_ci, lty = lty.se, lwd = lwd.se,
  28.                 col = col.se)
  29.         lines(x, lower_ci, lty = lty.se, lwd = lwd.se,
  30.                 col = col.se)
  31.     }
  32.     # The iy variable contains the ordering of the y-variable
  33.     # the x-variable is already ordered
  34.     se.polygon <- function(x, iy, i, ff = 2){
  35.         tt <- ff * terms$se.fit[iy, i]
  36.         upper_ci <- tms[iy, i] + tt
  37.         lower_ci <- tms[iy, i] - tt
  38.        
  39.         if (identical(yscale, "exponential")){
  40.             upper_ci <- exp(upper_ci)
  41.             lower_ci <- exp(lower_ci)
  42.         }
  43.        
  44.         current_i.backw <- order(x, decreasing = TRUE)
  45.         current_i.forw <- order(x, decreasing = FALSE)
  46.        
  47.         # The x-axel is always the same
  48.         x.poly <- c(x[current_i.forw] , x[current_i.backw])
  49.         # The y axel is based upin the current model
  50.         y.poly <- c(upper_ci[current_i.forw], lower_ci[current_i.backw])
  51.         polygon(x.poly , y.poly , col = col.se, border = NA)
  52.     }
  53.     plot.density <- function(xx){
  54.         # calculate the coordinates of the density function
  55.         density <- density( xx )
  56.         # the height of the densityity curve
  57.         max.density <- max(density$y)
  58.        
  59.         # transform the y-coordinates of the density
  60.         if (density.proportion >= 1){
  61.             warning("Can't have a density proportion of 100 % of the plot, recommended is less than 0.2")
  62.             density.proportion <- .1
  63.         }
  64.        
  65.         # Get the boundaries of the plot to
  66.         # put the density polygon at the x-line
  67.         yscale <- par("usr")[3:4]
  68.         # get the "length" and range of the y-axis
  69.         yspan <- max(yscale) - min(yscale)
  70.        
  71.         density_percent <- density$y/max.density
  72.         height <- density.proportion * density_percent * yspan  + min(yscale)
  73.         if (par("ylog")){
  74.             # For some odd reason the default log scale is 10-based
  75.             # when the y-scale is logarithmic
  76.             height <- 10^(height)
  77.         }
  78.        
  79.         ## plot the polygon
  80.         polygon( density$x , height, border = F, col = col.dens)
  81.     }
  82.     plot.rug <- function(xx){
  83.         n <- length(xx)
  84.         lines(rep.int(jitter(xx), rep.int(3, n)), rep.int(ylims[1L] +
  85.                                 c(0, 0.05, NA) * diff(ylims), n))
  86.         if (partial.resid)
  87.             lines(rep.int(xlims[1L] + c(0, 0.05, NA) * diff(xlims),
  88.                             n), rep.int(pres[, i], rep.int(3, n)))
  89.     }
  90.  
  91.     plot.factor <- function(i, ff, xx,
  92.             xlab, ylab, main){
  93.        
  94.         if (!is.null(model$na.action))
  95.             ff <- naresid(model$na.action, ff)
  96.         ll <- levels(ff)
  97.         xlims <- range(seq_along(ll)) + c(-0.5, 0.5)
  98.        
  99.         if (rug) {
  100.             xlims[1L] <- xlims[1L] - 0.07 * diff(xlims)
  101.             xlims[2L] <- xlims[2L] + 0.03 * diff(xlims)
  102.         }
  103.         tmp_ylims <- ylims
  104.         if (identical(yscale, "exponential")){
  105.             tmp_ylims <- exp(tmp_ylims)
  106.         }
  107.         plot(1, 0, type = "n", xlab = xlab,
  108.                 ylab = ylab, log=log,
  109.                 xlim = xlims, ylim = tmp_ylims,
  110.                 main = main, xaxt = "n",
  111.                 ...)
  112.        
  113.         if (use.factor.levels)
  114.             axis(1, at = seq_along(ll), labels = ll, ...)
  115.         else axis(1)
  116.         for (j in seq_along(ll)) {
  117.             ww <- which(ff == ll[j])[c(1, 1)]
  118.             jf <- j + c(-0.4, 0.4)
  119.            
  120.             # Plot confidence interval
  121.             if (se){
  122.                 if (se.type == "polygon"){
  123.                     se.polygon(jf, iy = ww, i = i)
  124.                 }else{
  125.                     se.lines(jf, iy = ww, i = i)
  126.                 }
  127.             }
  128.            
  129.             yvalues <- tms[ww, i]
  130.             if (identical(yscale, "exponential")){
  131.                 yvalues <- exp(yvalues)
  132.             }
  133.             lines(jf, yvalues, col = col.term, lwd = lwd.term,
  134.                     ...)
  135.         }
  136.     }
  137.    
  138.     plot.continuous <- function(i,
  139.             xx,
  140.             xlab, ylab, main){
  141.    
  142.        
  143.         if (!is.null(use.rows))
  144.             xx <- xx[use.rows]
  145.         xlims <- range(xx, na.rm = TRUE)
  146.         if (rug && rug.type != "density")
  147.             xlims[1L] <- xlims[1L] - 0.07 * diff(xlims)
  148.         oo <- order(xx)
  149.        
  150.         yvalues <- tms[, i]
  151.         tmp_ylims <- ylims
  152.         if (identical(yscale, "exponential")){
  153.             yvalues <- exp(yvalues)
  154.             tmp_ylims <- exp(tmp_ylims)
  155.         }
  156.         plot(range(xx), range(yvalues), type = "n", xlab = xlab,  log=log,
  157.                 ylab = ylab, xlim = xlims, ylim = tmp_ylims,
  158.                 main = main[i],
  159.                 ...)
  160.        
  161.         # Plot confidence interval
  162.         if (se){
  163.             if (se.type == "polygon"){
  164.                 se.polygon(xx[oo], iy = oo, i = i)
  165.             }else{
  166.                 se.lines(xx[oo], iy = oo, i = i)
  167.             }
  168.            
  169.         }
  170.        
  171.         lines(xx[oo], yvalues[oo],
  172.                 col = col.term, lwd = lwd.term)
  173.     }
  174.    
  175.     # Get the the terms that are of interest
  176.     which.terms <- terms
  177.     terms <- if (is.null(terms))
  178.                 predict(model, type = "terms", se.fit = se)
  179.             else predict(model, type = "terms", se.fit = se, terms = terms)
  180.  
  181.     # Get the data used for the rug
  182.     mf <- model.frame(model)
  183.     if (is.null(data))
  184.         data <- eval(model$call$data, envir)
  185.     if (is.null(data))
  186.         data <- mf
  187.    
  188.     tms <- as.matrix(if (se)
  189.                         terms$fit
  190.                     else terms)
  191.    
  192.     use.rows <- if (NROW(tms) < NROW(data))
  193.         match(rownames(tms), rownames(data))
  194.    
  195.     nmt <- colnames(tms)
  196.     # Remove interaction terms
  197.     if (any(grep(":", nmt) > 0)){
  198.         for(i in grep(":", nmt)){
  199.             warning(sprintf("The interaction term '%s' won't be displayed", nmt[i]))
  200.             nmt <- nmt[-i]
  201.         }
  202.     }
  203.    
  204.     n.tms <- length(nmt)
  205.    
  206.     cn <- parse(text = nmt)
  207.     if (!is.null(smooth))
  208.         smooth <- match.fun(smooth)
  209.     if (is.null(ylabs))
  210.         ylabs <- paste("Partial for", nmt)
  211.     if (is.null(main))
  212.         main <- ""
  213.     else if (is.logical(main))
  214.         main <- if (main)
  215.                     deparse(model$call, 500)
  216.                 else ""
  217.     else if (!is.character(main))
  218.         stop("'main' must be TRUE, FALSE, NULL or character (vector).")
  219.     main <- rep(main, length.out = n.tms)
  220.     pf <- envir
  221.     carrier <- function(term) {
  222.         if (length(term) > 1L)
  223.             carrier(term[[2L]])
  224.         else eval(term, data, enclos = pf)
  225.     }
  226.     carrier.name <- function(term) {
  227.         if (length(term) > 1L)
  228.             carrier.name(term[[2L]])
  229.         else as.character(term)
  230.     }
  231.     if (is.null(xlabs))
  232.         xlabs <- unlist(lapply(cn, carrier.name))
  233.     if (partial.resid || !is.null(smooth)) {
  234.         pres <- residuals(model, "partial")
  235.         if (!is.null(which.terms))
  236.             pres <- pres[, which.terms, drop = FALSE]
  237.     }
  238.     is.fac <- sapply(nmt, function(i){
  239.                 if (i %in% colnames(mf)){
  240.                     return(is.factor(mf[, i]))
  241.                 }
  242.                 cn <- grep(sprintf("(^%s$|^[a-zA-Z0-9]+[(][ ]*%s[, 0-9a-zA-Z\"\']+[)])", i, i), colnames(mf))
  243.                 if (length(cn)==0){
  244.                     stop(sprintf("Could not find '%s' in dataset", i))
  245.                 }else if (length(cn) > 1){
  246.                     cn <- cn[1]
  247.                     warning("More than one name match found")
  248.                 }
  249.                 return(is.factor(mf[, cn]))
  250.             })
  251.    
  252.     nb.fig <- prod(par("mfcol"))
  253.     if (ask) {
  254.         oask <- devAskNewPage(TRUE)
  255.         on.exit(devAskNewPage(oask))
  256.     }
  257.     ylims <- ylim
  258.     if (identical(ylims, "common")) {
  259.         ylims <- if (!se)
  260.                     range(tms, na.rm = TRUE)
  261.                 else range(tms + 1.05 * 2 * terms$se.fit, tms - 1.05 *
  262.                                     2 * terms$se.fit, na.rm = TRUE)
  263.         if (partial.resid)
  264.             ylims <- range(ylims, pres, na.rm = TRUE)
  265.         if (rug)
  266.             ylims[1L] <- ylims[1L] - 0.07 * diff(ylims)
  267.     }
  268.    
  269.     for (i in 1L:n.tms) {
  270.         if (identical(ylim, "free")) {
  271.             ylims <- range(tms[, i], na.rm = TRUE)
  272.             if (se)
  273.                 ylims <- range(ylims, tms[, i] + 1.05 * 2 * terms$se.fit[,
  274.                                 i], tms[, i] - 1.05 * 2 * terms$se.fit[, i],
  275.                         na.rm = TRUE)
  276.             if (partial.resid)
  277.                 ylims <- range(ylims, pres[, i], na.rm = TRUE)
  278.             if (rug)
  279.                 ylims[1L] <- ylims[1L] - 0.07 * diff(ylims)
  280.         }
  281.        
  282.         if (is.fac[i]) {
  283.             ff <- mf[, nmt[i]]
  284.             xx <- as.numeric(mf[, nmt[i]])
  285.             plot.factor(i,
  286.                     ff=ff,
  287.                     xx=xx,
  288.                     xlab=xlabs[i], ylab=ylabs[i],
  289.                     main=main[i])
  290.         }
  291.         else {
  292.             xx <- carrier(cn[[i]])
  293.             plot.continuous(i, xx=xx,
  294.                     xlab=xlabs[i],
  295.                     ylab=ylabs[i],
  296.                     main=main[i])
  297.            
  298.         }
  299.         if (partial.resid) {
  300.             if (!is.fac[i] && !is.null(smooth)) {
  301.                 smooth(xx, pres[, i], lty = lty.smth, cex = cex,
  302.                         pch = pch, col = col.res, col.smooth = col.smth,
  303.                         span = span.smth)
  304.             }
  305.             else points(xx, pres[, i], cex = cex, pch = pch,
  306.                         col = col.res)
  307.         }
  308.        
  309.         if (rug){
  310.             if (rug.type == "density") {
  311.                 plot.density(xx)
  312.             }else {
  313.                 plot.rug(xx)
  314.             }
  315.            
  316.         }
  317.     }
  318.     invisible(n.tms)
  319. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement