Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Placing the grid along date tickmarks

Tags:

r

strptime

I have the following data:

x=strptime(20010101:20010110)
y=1:10
z=data.frame(x,y)

So my data is this:

            x  y
1  2001-01-01  1
2  2001-01-02  2
3  2001-01-03  3
4  2001-01-04  4
5  2001-01-05  5
6  2001-01-06  6
7  2001-01-07  7
8  2001-01-08  8
9  2001-01-09  9
10 2001-01-10 10

When I create a plot in base using:

plot(x,y)
grid(NULL,NULL)

My vertical grid does not align with the date tick marks. I know this seems like a pretty simple problem, but I have not found a solution to this anywhere. Is there a way to get the vertical grid to align with the date tick marks using base that does not require me to do this:

abline(v=as.numeric(strptime(c(20010102,20010104,20010106,20010108,20010110),'%Y%m%d')))

I have a lot of plots with different dates and I would really like to automate this as much as possible, hopefully using base.

like image 947
thequerist Avatar asked Feb 02 '12 20:02

thequerist


4 Answers

The function axis draws your axes, tick marks and labels, and returns the tick mark positions as a vector.

Since you have Date data, you need to use axis.Date to do this, and then use abline to plot the grid:

z=data.frame(
  x=seq(as.Date("2001-01-01"), by="+1 month", length.out=10)
  y=1:10
)
plot(y~x, data=z)
abline(v=axis.Date(1, z$x), col="grey80")

enter image description here

like image 127
Andrie Avatar answered Nov 03 '22 00:11

Andrie


abline can extract the date ticks from your POSIXlt vector (via strptime).

x=strptime(20010101:20010110,format="%Y%m%d")
y=1:10

plot(x,y)
grid(nx=NA, ny=NULL)
abline(v=axis.POSIXct(1, x=pretty(x)),col = "lightgray", lty = "dotted", lwd = par("lwd"))

I would suggest creating your own function which would add both horizontal and vertical grids.

my.grid <-function(){
grid(nx=NA, ny=NULL)
abline(v=axis.POSIXct(1, x=pretty(x)),col = "lightgray", lty = "dotted", lwd =
par("lwd"))
}

plot(x,y)
my.grid()
like image 20
Pierre Lapointe Avatar answered Nov 03 '22 01:11

Pierre Lapointe


As the ?grid help file says, "if more fine tuning is required, [you can] use abline(h = ., v = .) directly". It's a little bit more work, but not much, and would be easy enough to wrap up in a function if you want to use it often.

Here's one way to do it:

plot(x,y)
abline(v = pretty(extendrange(z$x)), 
       h = pretty(extendrange(z$y)),
       col = 'lightgrey', lty = "dotted")
points(x,y, pch=16)

enter image description here

like image 20
Josh O'Brien Avatar answered Nov 03 '22 01:11

Josh O'Brien


I'm not familiar with the intricacies of the base plots. But, ggplot does this effectively.

x <- strptime(20010101:20010110, format='%Y%m%d')
y <- 1:10
z <- data.frame(x, y)
qplot(x,y,data=z,'point')
like image 39
Justin Avatar answered Nov 03 '22 01:11

Justin