Placing the grid along date tickmarks

前端 未结 4 1393
情歌与酒
情歌与酒 2021-01-18 08:31

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  2         


        
相关标签:
4条回答
  • 2021-01-18 08:42

    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')
    
    0 讨论(0)
  • 2021-01-18 08:45

    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

    0 讨论(0)
  • 2021-01-18 08:48

    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

    0 讨论(0)
  • 2021-01-18 08:51

    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()
    
    0 讨论(0)
提交回复
热议问题