Setting xlim with dates in R

M. Bittner picture M. Bittner · Sep 2, 2016 · Viewed 16.7k times · Source

I need to set the x-axis limit of a plot in R, but my values are dates (%m/%d/%Y format). How would I go about changing this? I am trying to plot trophic position vs. collection date. All of my collection dates are in date format (%m/%d/%Y)

This is the code I have tried:

plot(Trophic_Position~Collection_Date, data=BO,main="Burr Oak", col="red",xlab="Collection date",ylab="Trophic Position", xlim=c("6/09/2014","8/30/2014"), ylim=c(2,5))

I have just started to learn R, so I know that there must be a code that goes along with the xlim command, but I haven't been able to find out what code applies to my situation.

Answer

Ebby picture Ebby · Jul 16, 2020

Try using ggplot2. Your figure with required restricted X values - date can be obtained from,

library(ggplot2)

g1 = ggplot(ENTER_YOUR_DATAFRAME_NAME, aes(x=Collection_Date, y=B0))+geom_line()
g1+ scale_x_date(limits = as.Date(c("2014-06-09","2014-08-30")))