This document explains state space time series related plotting using ggplot2 and ggfortify.
First, install ggfortify from github.
library(devtools)
install_github('sinhrks/ggfortify')
{dlm} packageggfortify let ggplot2 know how to interpret {dlm} instances. After loading ggfortify, you can use ggplot2::autoplot to plot them.
library(ggplot2)
library(ggfortify)
autoplot draws both original and fitted time series, because dlm::dlmFilter contains them.
library(dlm)
form <- function(theta){
dlmModPoly(order = 1, dV = exp(theta[1]), dW = exp(theta[2]))
}
model <- form(dlmMLE(Nile, parm = c(1, 1), form)$par)
filtered <- dlmFilter(Nile, model)
autoplot(filtered)
You can specify some options to change how plot looks, such as ts.linetype and fitted.colour. Use help(autoplot.tsmodel) (or help(autoplot.*) for any other objects) to check available options.
autoplot(filtered, ts.linetype = 'dashed', fitted.colour = 'blue')
ggfortify can plot dlm::dlmSmooth instance which returns a list instance using using class inference. Note that only smoothed result is plotted because dlm::dlmSmooth doesn’t contain original ts.
smoothed <- dlmSmooth(filtered)
class(smoothed)
## [1] "list"
autoplot(smoothed)
To plot original ts, filtered result and smoothed result, you can useautoplot as below. When autoplot accepts ggplot instance via p option, continuous plot is drawn on the passed ggplot.
p <- autoplot(filtered)
autoplot(smoothed, ts.colour = 'blue', p = p)
{KFAS} packageYou can use autoplot in almost the same manner as {dlm}. Note that autoplot draws smoothed result if it exists in KFAS::KFS instance, and KFAS::KFS contains smoothed result by default.
library(KFAS)
model <- SSModel(
Nile ~ SSMtrend(degree=1, Q=matrix(NA)), H=matrix(NA)
)
fit <- fitSSM(model=model, inits=c(log(var(Nile)),log(var(Nile))), method="BFGS")
smoothed <- KFS(fit$model)
autoplot(smoothed)
If you want filtered result, specify smoothing='none' when calling KFS. For details, see help(KFS).
filtered <- KFS(fit$model, filtering="mean", smoothing='none')
autoplot(filtered)
Also, KFAS::signal will retrieve specific state from KFAS::KFS instance. The result will be a list which contains the retrieved state as ts in signal attribute. ggfortify can autoplot it using class inference.
trend <- signal(smoothed, states="trend")
class(trend)
## [1] "list"
Because signal is a ts instance, you can use autoplot and p option as the same as dlm::dlmSmooth example.
p <- autoplot(filtered)
autoplot(trend, ts.colour = 'blue', p = p)