R Plot: ggplot2 extensions for ts objects

From OnnoWiki
Jump to navigation Jump to search
install.packages(
  c("ggfortify", "changepoint",
    "strucchange", "ggpmisc")
)

Then use the autoplot.ts() function to visualize time series objects, as follow:

library(ggfortify)
library(magrittr) # for piping %>%
# Plot ts objects
autoplot(AirPassengers)
# Identify change points in mean and variance
AirPassengers %>%
  changepoint:: cpt.meanvar() %>%  # Identify change points
  autoplot()
# Detect jump in a data
strucchange::breakpoints(Nile ~ 1) %>%
  autoplot()

Detect peaks and valleys:

library(ggpmisc)
ggplot(lynx, as.numeric = FALSE) + geom_line() + 
  stat_peaks(colour = "red") +
  stat_peaks(geom = "text", colour = "red", 
             vjust = -0.5, x.label.fmt = "%Y") +
  stat_valleys(colour = "blue") +
  stat_valleys(geom = "text", colour = "blue", angle = 45,
               vjust = 1.5, hjust = 1,  x.label.fmt = "%Y")+
  ylim(-500, 7300)


Referensi

Pranala Menarik