dat <- t(harborSeal)
dat <- dat[c(2, 11, 12), ]
fit <- MARSS(dat, model = list(Z = factor(c("WA", "OR", "OR"))))
library(ggplot2)
theme_set(theme_bw())
if (FALSE) {
# Show a series of standard residuals diagnostic plots for state-space models
autoplot(fit, plot.type="residuals")
}
d <- residuals(fit, type="tt1")
if (FALSE) {
# Make a series of diagnostic plots from a residuals object
autoplot(d)
}
# Manually make a plot of the model residuals (innovations) with intervals
d$.conf.low <- d$.fitted+qnorm(0.05/2)*d$.sigma
d$.conf.up <- d$.fitted-qnorm(0.05/2)*d$.sigma
ggplot(data = d) +
geom_line(aes(t, .fitted)) +
geom_point(aes(t, value), na.rm=TRUE) +
geom_ribbon(aes(x = t, ymin = .conf.low, ymax = .conf.up), linetype = 2, alpha = 0.1) +
ggtitle("Model residuals (innovations)") +
xlab("Time Step") + ylab("Count") +
facet_grid(~.rownames)
# NOTE state residuals are for t to t+1 while the value and fitted columns
# are for t. So (value-fitted)[t] matches .resids[t+1] NOT .resids[t]
# This is only for state residuals. For model residuals, the time-indexing matches.
d <- residuals(fit, type="tT")
dsub <- subset(d, name=="state")
# note t in col 1 matches t+1 in col 2
head(cbind(.resids=dsub$.resids, valminusfitted=dsub$value-dsub$.fitted))
# Make a plot of the smoothation residuals
ggplot(data = d) +
geom_point(aes(t, value-.fitted), na.rm=TRUE) +
facet_grid(~.rownames+name) +
ggtitle("Smoothation residuals (state and model)") +
xlab("Time Step") + ylab("Count")
# Make a plot of xtT versus prediction of xt from xtT[t-1]
# This is NOT the estimate of the smoothed states with CIs. Use tsSmooth() for that.
ggplot(data = subset(d, name=="state")) +
geom_point(aes(t, value), na.rm=TRUE) +
geom_line(aes(x = t, .fitted), color="blue") +
facet_grid(~.rownames) +
xlab("Time Step") + ylab("Count") +
ggtitle("xtT (points) and prediction (line)")
# Make a plot of y versus prediction of yt from xtT[t]
# Why doesn't the OR line go through the points?
# Because there is only one OR state line and it needs to go through
# both sets of OR data.
ggplot(data = subset(d, name=="model")) +
geom_point(aes(t, value), na.rm=TRUE) +
geom_line(aes(x = t, .fitted), color="blue") +
facet_grid(~.rownames) +
xlab("Time Step") + ylab("Count") +
ggtitle("data (points) and prediction (line)")
Run the code above in your browser using DataLab