John
John

Reputation: 1947

How to put dates on x axis with ggplot?

Let's consider data :

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

I want to plot apple variable using ggplot, so :

ggplot()+aes(x=1:length(apple), y = apple)+geom_line()

enter image description here

However I don't know how to put dates on x axis instead of number of observation. Dates are stored in AAPL data frame :

head(AAPL)
           AAPL.Open AAPL.High AAPL.Low AAPL.Close AAPL.Volume AAPL.Adjusted
2013-01-02  19.77929  19.82143 19.34393   19.60821   560518000      17.06525
2013-01-03  19.56714  19.63107 19.32143   19.36071   352965200      16.84985
2013-01-04  19.17750  19.23679 18.77964   18.82143   594333600      16.38050
2013-01-07  18.64286  18.90357 18.40000   18.71071   484156400      16.28414
2013-01-08  18.90036  18.99607 18.61607   18.76107   458707200      16.32798
2013-01-09  18.66071  18.75036 18.42822   18.46786   407604400      16.07279

But I don't know how to extract those dates. Do you hany any idea how it can be done ?

Upvotes: 0

Views: 434

Answers (2)

G. Grothendieck
G. Grothendieck

Reputation: 270170

Use autoplot.zoo as shown below. Replace Cl with Ad if you want the adjusted close.

See ?autoplot.zoo for more info.

library(ggplot2)
library(quantmod)

getSymbols("AAPL")
autoplot(Cl(AAPL))

It would be possible to customize the X axis, e.g.

autoplot(Cl(AAPL)) + scale_x_date(date_labels = "%Y", breaks = "year")

but the default without that may be sufficient.

Here is the output using the default.

screenshot

Upvotes: 2

Ian Campbell
Ian Campbell

Reputation: 24878

In a zoo object, the dates are stored in custom attributes, but that won't work easily with ggplot.

class(apple)
[1] "xts" "zoo"

You can actually access those dates with the zoo::index function:

head(zoo::index(apple))
[1] "2013-01-02" "2013-01-03" "2013-01-04" "2013-01-07" "2013-01-08" "2013-01-09"

Another approach is to convert to a data frame which will place the dates into the row names and then convert those row names to a column with tibble::rownames_to_column:

library(dplyr)
library(tibble)
apple %>%
  as.data.frame() %>%
  rownames_to_column("Date") %>%
  mutate(Date = as.Date(Date)) %>%
ggplot(aes(x = Date, y = AAPL.Close)) +
  geom_line()

enter image description here

Upvotes: 2

Related Questions