Question

I need to plot a graph where on the x axis is a date and on y axis a corresponding stock price. The date in my dataframe is numerical. 1980-01-01 for example is 3653. When I plot the data I get years on the x axis. However I would like to specify which years should be there. When I set my own x axis through axis(1, at=c("1980","1985","1990","1995","2000","2005","2010")) I get an error.

Do I have to modify data or what is the trick to get this working?

This is how the data looks:

    > data2
            date    close   change  color
        1   3653    4.668333    NA  NA
        2   3658    4.699753    3.142007e-02    green
        3   3665    4.710161    1.040780e-02    green
        4   3672    4.732772    2.261090e-02    green
        5   3679    4.745975    1.320353e-02    green
        6   3686    4.770261    2.428574e-02    green
        7   3693    4.748491    -2.176980e-02   red
...

Here is what I have so far. You need tseries and zoo package.

data <- get.hist.quote("^GSPC", start = "1980-01-01", compression="w")
data2 <- data.frame( date = as.Date(index(data)), close = data$Close)
data2$close <- log(data2$close)
plot(data2$date, data2$close, type="h", main="S&P 500", ylab="Log Close", xlab="Date",
     axes=F)
axis(2, at=c("5.0","5.5","6.0","6.5","7.0"))
box(which = "plot") 
Was it helpful?

Solution

Use as.Date with the appropriate origin to convert the dates to "Date" class. For exmaple,

> as.Date(3653, origin = "1969-12-31")
[1] "1980-01-01"

(Normally the origin in R is "1970-01-01" so you might want to check if you are off by one.)

Anyways, continuing:

data2$Date <- as.Date(data2$date, origin = "1969-12-31")

plot(close ~ Date, data2, type = "o", pch = 20, xaxt = "n")

lab <- seq(1980, 2010, 5) # years
at <- as.Date(paste0(lab, "-01-01"))
axis(1, at, lab)

OTHER TIPS

I think you need to put where you want your ticks so 1:7 and 1:5 with the at=... argument, and use the argument labels=... to put the years.

Example:

plot(1:7,c(1:5,5,5),axes=F,xlab="",ylab="")
axis(1,at=1:7, labels=c("1980","1985","1990","1995","2000","2005","2010"))
axis(2,at=1:5)

I hope this will help.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top