How to use ggplot2 and Tidyverse to graph more than one stock in a time series...

The last question of this semester, I promise. How can I make a ggplot2 showing all three of these stocks?


start = as.Date("2014-02-01")
end = as.Date("2020-03-31")

getSymbols(c("JPM", "C", "WFC"), src = "yahoo",
from = start, to = end)

stocks = as.xts(data.frame(C = C[, "C.Adjusted"], JPM = JPM[, "JPM.Adjusted"], WFC = WFC[, "WFC.Adjusted"]))

names(stocks) = c("Citi", "JP Morgan", "Wells Fargo")
index(stocks) = as.Date(index(stocks))

I am supposed to make two graphs in two different colors themes and all three stocks must be on the same graph, but I am stuck here:

stocks_series = tidy(stocks) %>%
ggplot(aes(x=index,y=value, color=series)) + geom_line()

Not sure I understand your question. Your code does make a graph with all three stocks.

If you want to plot the stocks in separate graphs but using the same axes, you can use faceting:

tidy(stocks) %>%
  ggplot(aes(x=index,y=value)) +
  geom_line() +

And if you really want the axes to be different, you can make each plot separately and combine them either with cowplot or directly in your final document. Something like

tidy(stocks) %>%
  filter(series == "Citi") %>%
  ggplot(aes(x=index,y=value)) +

citi <- tidy(C[, "C.Adjusted"]) %>%
ggplot(aes(x=index,y=value)) +

jpm <- tidy(JPM[, "JPM.Adjusted"]) %>%
ggplot(aes(x=index,y=value)) +

wfc <- tidy(WFC[, "WFC.Adjusted"]) %>%
ggplot(aes(x=index,y=value)) +

citi/jpm/wfc # Stack plots

1 Like

Are you seeing three lines when you run the code? All I get is a blank white space where the graph should be for some reason. Yes, all three lines need to be on the same graph. I do not understand what is going on.

Oh it's probably because you're saving the plot in a variable instead of displaying it (as KenatRSF shows).

There are two ways to display ggplot graphs. One is to execute the command directly without saving in a variable:

ggplot() +

The other is to save in a variable, but then you still have to display the content of the variable.

stock_series <- ggplot() +
  geom_line(aes(x=x,y=y))    # create initial plot

stock_series <- stock_series + theme_classic()    # you can add to it if you want

# Finally, display it!

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.