7

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.

M. Bittner
  • 71
  • 1
  • 1
  • 2
  • 8
    You need to provide the `xlim` values in Date format, rather than as character strings: `xlim=as.Date(c("2014-06-09", "2014-08-30"))`. – eipi10 Sep 02 '16 at 19:26
  • @eipi10 you should post this as an answer so it can be accepted as the right answer. – AndiAna Apr 28 '22 at 05:52

2 Answers2

2

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")))
Dharman
  • 30,962
  • 25
  • 85
  • 135
Ebby
  • 141
  • 1
  • 4
0

(credits to @eipi10 in the comments section)

You need to provide the xlim values in Date format, rather than as character strings:

xlim=as.Date(c("2014-06-09", "2014-08-30"))
Sridhar Sarnobat
  • 25,183
  • 12
  • 93
  • 106