Search code examples
rggplot2quantmod

How to combine two graphs created by autoplot?


Let's consider two financial assets (apple and gold) :

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

Let's see how the plots of apple and gold look like :

autoplot(Cl(AAPL))

enter image description here

autoplot(Cl(GOLD))

enter image description here

However I don't know how can I have them both on one graph. I was trying to search for a solution but none of them is using autoplot() function. Is this feasible to have two of the above graphs on one coordinate system ?

I'm looking for something like this but created with autoplot()

ggplot()+geom_line(aes(x = 1:945, y = Cl(AAPL)))+geom_line(aes(x = 1:945, y = Cl(GOLD)))

enter image description here


Solution

  • Using e.g. patchwork this could be achieved like so:

    start <- as.Date("2013-01-01")
    end <- as.Date("2016-10-01")
    library(quantmod)
    
    library(ggplot2)
    getSymbols("AAPL", src = "yahoo", from = start, to = end)
    
    #> [1] "AAPL"
    getSymbols("GOLD", src = "yahoo", from = start, to = end)
    #> [1] "GOLD"
    
    library(patchwork)
    
    p1 <- autoplot(Cl(AAPL))
    p2 <- autoplot(Cl(GOLD))
    p1 + p2
    

    EDIT Following the example in docs of zoo::autopilot.zoo you could make your plot manually using ggplot2 like so:

    ggplot(mapping = aes(x = Index, y = Value)) +
      geom_line(data = fortify(Cl(AAPL), melt = TRUE), aes(color = "AAPL")) + 
      geom_line(data = fortify(Cl(GOLD), melt = TRUE), aes(color = "GOLD")) + 
      xlab("Index") + ylab("x")