Search code examples
rggplot2quantmod

Simple way to shorten time period of graph in ggplot


Let's consider data :

library(ggplot2)
library(quantmod)
start <- as.Date("2013-01-01")
end <- as.Date("2016-10-01")
# Apple stock
getSymbols("AAPL", src = "yahoo", from = start, to = end) 

And plot :

autoplot(Cl(AAPL))

enter image description here

My question is : is there any way how can I simlpy shorten time period of my plot ? Let's say for example I want to have my plot from '2013-01-01' up to '2014-01-01'. Of course I can do exactly same thing with changing my start and end variables (defined at the very beggining) and redownload data set. However I found this solution inefficient. Is there any simpler way how it can be performed ?


Solution

  • There are two approaches. One is to specify limits to the plotting routine and the other is to subset the data itself. Since the first one is already illustrated by another answer we will focus on the second:

    # xts suppports .../... notation
    apple <- Cl(AAPL)['2013-01-01/2014-01-01']
    
    # this will extract all rows for 2013
    apple <- Cl(AAPL)['2013']
    
    # window function
    apple <- window(Cl(AAPL), start = "2013-01-01", end = "2014-01-01")
    

    Having defined apple we can autoplot it.