2

I have the following data (part of my data):

 Date         Cases
   <date>      <dbl>
 1 2020-03-02     3
 2 2020-03-03    12
 3 2020-03-04     2
 4 2020-03-05     4
 5 2020-03-06    19
 6 2020-03-07    19
 7 2020-03-08    21
 8 2020-03-09    49
 9 2020-03-10    36
10 2020-03-11    34

I would like to plot the date with the cases where the x-axis shows the day and the month only.

I tried this:

plot(Cases~as.Date(Date),type="l",
     xlab="Date",ylab="Cases")

But it shows me the Month only without a date.

  • Does this answer your question? [Plotting time-series with Date labels on x-axis](https://stackoverflow.com/questions/4843969/plotting-time-series-with-date-labels-on-x-axis) – devin-wang Jun 19 '20 at 07:18
  • @devin-wang thank you so much for your help. I tried it but, it gave me this: `Warning message: In as.POSIXlt.POSIXct(x, tz = tz) : unknown timezone '%m/%d/%Y'` –  Jun 19 '20 at 07:27
  • This code works as expected in my case, with no warning message. `plot(Cases ~ Date, df, type="l", xaxt="n"); axis(1, df$Date, format(df$Date, "%m/%d/%Y"), cex.axis = .7)` – devin-wang Jun 19 '20 at 09:10
  • @devin-wang Thanks for your comment. That may be because you use only a subset of my data set. However, when, I apply it to my data, I got the warning message every time, I run the code. I tried many other codes on this website and they did not work for my data. –  Jun 19 '20 at 13:10

1 Answers1

0

The as.Date(Date) gives an object with class "Date" and, thus, calls a different plot.* method than you expect. You could omit x-axis using xaxt="n" and rebuild it with axis and mtext. The axTicks function helps to get pretty tick marks.

with(dat, plot(Cases ~ as.Date(Date), type="l", xlab="Date", xaxt="n", ylab="Cases"))
at. <- axTicks(1)
axis(1, at=at., labels=F)
mtext(strftime(dat$Date, format="%d.%m.")[match(as.numeric(as.Date(dat$Date)), 
                                                at.)], 1, 1, at=at.)

enter image description here

jay.sf
  • 60,139
  • 8
  • 53
  • 110