I was trying to plot two columns of my data.frame
(let's call them data$Date
, data$x
for convenience).
When plotting data$x
I want to limit myself to data from after 2014-01-01
. What's the proper way of doing that?
I was trying to plot two columns of my data.frame
(let's call them data$Date
, data$x
for convenience).
When plotting data$x
I want to limit myself to data from after 2014-01-01
. What's the proper way of doing that?
You can first put your Date
column as Date with strptime
and then subset your data.frame to keep only dates post 2014-01-01:
data$Date <- strptime(data$Date, format="%y%y-%m-%d")
plot(data$Date[data$Date > strptime("2014-01-01", format="%y%y-%m-%d")], data$x[data$Date > strptime("2014-01-01", format="%y%y-%m-%d")], las=1, pch=19, xlab="Date post 01/01/2014", ylab="")
Example
data <- data.frame(Date=c("2013-02-03","2013-12-13","2014-02-02","2014-05-05"), x=1:4, stringsAsFactors=F)
EDIT
If you need to plot more than one "x
", you can first use plot
and then points
. You can adjust the x axis
with axis.POSIXct
:
data <- data.frame(Date=c("2013-02-03", "2013-12-13", "2014-02-02", "2014-05-05", "2015-04-14"), x1=rep(1, 5), x2=rep(2, 5), stringsAsFactors=F)
data$Date <- strptime(data$Date, format="%y%y-%m-%d")
plot(data$Date[data$Date > strptime("2014-01-01", format="%y%y-%m-%d")], data$x1[data$Date > strptime("2014-01-01", format="%y%y-%m-%d")], las=1, pch=19, col="red", xlab="Date post 01/01/2014", ylab="", xaxt="n", ylim=c(0,3))
points(data$Date[data$Date > strptime("2014-01-01", format="%y%y-%m-%d")], data$x2[data$Date > strptime("2014-01-01", format="%y%y-%m-%d")], pch=19, col="blue")
axis.POSIXct(1, at=seq(strptime("2014-02-01",format="%y%y-%m-%d"),strptime("2015-04-01",format="%y%y-%m-%d"), by = "month"), format = "%m/%y")
If your data frame stores the date as a standard date type, you can also set the xlim option in plot using the date type, e.g.:
xlim<-c(as.Date("20140101","%Y%m%d"),as.Date("20180801","%Y%m%d"))
plot(data$Date,data$x,xlim=xlim)