Home > Enterprise >  Save only one plot from tsdiag
Save only one plot from tsdiag

Time:11-24

I would like to retrieve and save to file only one plot out three from tsdiag function.

enter image description here

How can I achieve that? I've been trying to use additional parameter which but the plotting function is still returning the whole diagnosis.

tsdiag(arima_model, which = 1)  # does not work

I couldn't find anything in the documentation of stats either. It's quite easy to reproduce these plots manually but it would be great to get only one of them.

CodePudding user response:

R is open source, so one can have a look in the sources and check if it is possible to create an own user-modified function.

The tsdiagfunction is found in package stats, source file ama0.R. Here a hacked version that supports a which-argument:

## modified from R package stats, file `ama0.R`
tsdiag.Arima <- tsdiag.arima0 <- function(object, gof.lag = 10, which = 1L:3L, ...) {
  ## plot standardized residuals, acf of residuals, Ljung-Box p-values
  oldpar <- par(mfrow = c(length(which), 1))
  on.exit(par(oldpar))
  rs <- object$residuals
  if (1L %in% which) {
    stdres <- rs/sqrt(object$sigma2)
    plot(stdres, type = "h", main = "Standardized Residuals", ylab = "")
    abline(h = 0)
  }
  if (2L %in% which) {
    acf(object$residuals, plot = TRUE, main = "ACF of Residuals",
        na.action = na.pass)
  }
  if (3L %in% which) {
    nlag <- gof.lag
    pval <- numeric(nlag)
    for(i in 1L:nlag) pval[i] <- Box.test(rs, i, type="Ljung-Box")$p.value
    plot(1L:nlag, pval, xlab = "lag", ylab = "p value", ylim = c(0,1),
         main = "p values for Ljung-Box statistic")
    abline(h = 0.05, lty = 2, col = "blue")
  }
} 

Now we can test it:

library("forecast")   # contains auto.arima
library("boot")       # contains manaus data set

m <- auto.arima(manaus)

tsdiag(m)             # all plots
tsdiag(m, which=1)    # only 2nd
tsdiag(m, which=2:3)  # plot 2 and 3
  • Related