Ch11 Graphics for time series

11.2 Graphics for a single time series
11.3 Multiple series
11.4 Special features of time series

 

Graphics for a single time series | 225

data(Bundesliga, package="vcd")
goals <- Bundesliga %>% group_by(Year) %>%
         summarise(hg=sum(HomeGoals), ag=sum(AwayGoals),
         ng=n(), avg=(hg+ag)/ng)
library(mgcv)
ggplot(goals, aes(Year, avg)) + geom_point() + geom_line() +
       stat_smooth(method = "gam", formula = y ~ s(x)) +
       ylim(2,4) + xlab("") + ylab("") +
       ggtitle("Bundesliga goals per game by year")

 

ggplot(goals) + geom_line(aes(Year, hg/ng), colour="red") +
      geom_line(aes(Year, ag/ng), colour="blue") +
      ylim(0.5, 2.5) + xlab("") + ylab("")

 

226

library(zoo)
data(GermanUnemployment, package="AER")
ge <- as.zoo(GermanUnemployment)
autoplot(ge$unadjusted) + xlab("") + ylab("")

 

Multiple series | 227

data(Nightingale, package="HistData")
ggplot(Nightingale, aes(Date)) +
       geom_line(aes(y=Disease.rate)) +
       geom_point(aes(y=Disease.rate), size=2) +
       geom_line(aes(y=Wounds.rate), size=1.3, col="red",
       linetype="dashed") +
       geom_line(aes(y=Other.rate), size=1.3, col="blue",
       linetype="dotted") + ylab("Death rates")

 

229

library(FinCal); library(reshape2)
sh13 <- get.ohlcs.google(symbols=c("AAPL","GOOG","IBM","MSFT"),
                         start="2013-01-01",end="2013-12-31")
SH13 <- with(sh13, data.frame(date = as.Date(AAPL$date), 
                              Apple = AAPL$close,
                              Google = GOOG$close, 
                              IBM = IBM$close, 
                              Microsoft = MSFT$close))
SH13a <- lapply(select(SH13, -date), function(x) 100*x/x[1])
SH13a <- cbind(date = SH13$date, as.data.frame(SH13a))
SH13am <- melt(SH13a, id="date", variable.name="share",
               value.name="price")
ggplot(SH13am, aes(date, y=price, colour=share,
       group=share)) + geom_line() + xlab("") + ylab("") +
       theme(legend.position="bottom") +
       theme(legend.title=element_blank())

 

231

data(hydroSIMN, package="nsRFA")
annualflows <- within(annualflows, cod <- factor(cod))
ggplot(annualflows, aes(anno, dato, group=cod, colour=cod)) +
       geom_line()  + xlab("")  + ylab("") + theme(legend.position="none")

 

232

ggplot(annualflows,
       aes(anno, dato, group=cod, colour=cod)) +
       geom_line() + xlab("")  + ylab("") + 
       facet_wrap(~cod) + theme(legend.position="none")

 

Special features of time series | 234

data(VonBort, package="vcd")
horses <- VonBort %>% group_by(year) %>%
          summarise(totalDeaths=sum(deaths))
ggplot(horses, aes(year, totalDeaths)) +
       geom_bar(stat="identity") + ylim(0,20)

 

235

data(lynx)
library(zoo)
autoplot(as.zoo(lynx)) + geom_point()

 

236

library(forecast)
par(las=1, mar=c(3.1, 4.1, 1.1, 2.1)) 
fit <- ets(ge$unadjusted)
plot(forecast(fit), main="")