2
votes

I am new in plotting time series. I downloaded a time series data and calculated a linear equation and I would like to add it in the time series plot. I want to show the year in the plot so I used index(stk) as x-axis input.

code:

library(quantmod)

stk <- suppressWarnings(getSymbols("AAPL", auto.assign = FALSE,
                                   src = "yahoo", periodicity = "daily"))
stk <- na.omit(stk)

stk.lm1 <- lm(log(Cl(stk)) ~ c(1:nrow(stk)), data = stk)
plot(index(stk), log(Cl(stk)), type = "l", lwd = 3, las = 1)
abline(coefficients(stk.lm1)[1], coefficients(stk.lm1)[2], col="blue")

I know it is the plot using index(stk), how can I do to keep the x axis of plot in date and can I use plot.xts or other like ggplot2 to do the same things? Please advise, thank you very much.

2

2 Answers

1
votes

It isn't dificult to do the plot that you want in base r plot or ggplot2 here is what you what:

plot(index(stk), log(Cl(stk)), type="l", lwd=3, las=1)
lines(x = index(stk.lm1$fitted.values), y = stk.lm1$fitted.values,col = "blue")

for the base r plot I added a line with the fitted values of the linear regression that I extracted with the $ signed and the dates of theme. Take into account that lm respect the structure of the data so the results are xts

library(ggplot2)
ggplot(stk, aes(x = index(stk), y = as.numeric(log(Cl(stk)))))+geom_line(lwd=1)+
  geom_line(aes(x = index(stk.lm1$fitted.values), y = stk.lm1$fitted.values),col = "blue")+
  labs(x = "Date", y = "Log Price")

For ggplot2 is quite similar. First you have to initiate the plot with ggplot where you defined the data and aesthetics (aes), then you add a line with geom_line and for the extra line I used the this command and define the new line in a new aes the same way I did it with the base r function.

1
votes

Here's a ggplot solution. You shouldn't have to calculate the linear regression coefficients yourself:

# convert stk to data frame & specify your x-axis variable explicitly
stk.df <- as.data.frame(stk)
stk.df$Date <- as.Date(rownames(stk.df))

# plot
ggplot(stk.df,
       aes(x = Date, y = log(AAPL.Close))) +
  geom_line() +
  geom_smooth(method = "lm", se = FALSE) +             
  labs(x = "Year", y = "log(AAPL's closing value)") +
  theme_bw()

The geom_smooth line takes care of the regression. Set se = TRUE if you want to include a confidence interval around the line.

plot