0

I'm trying to create a simple time series plot in R with the following data (it's in tbl format):

    Date          sales
  <date>        <dbl>
1 2010-02-05 1105572.
2 2010-09-03 1048761.
3 2010-11-19 1002791.
4 2010-12-24 1798476.
5 2011-02-04 1025625.
6 2011-11-18 1031977.

When I use the following command: plot(by_date$Date, by_date$sales, type = 'l'), the resulting graph just skips the individual dates, as I want it to display, and just shows the year on the x-axis, like this (please ignore the axis labels for now):

enter image description here

I've checked the format of the date column using class(by_date$Date) and it does show up as 'Date'. I've also checked other threads here and the closest one that came to answering my query is the one here. Tried that approach but didn't work for me, while plotting in ggplot or converting data to data frame didn't work either. Please help, thanks.

Cat_Dog
  • 43
  • 7

1 Answers1

0

With ggplot this should work -

library(ggplot2)
ggplot(by_date, aes(Date, sales)) + geom_line()

You can use scale_x_date to format your x-axis as you want.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • I did mention in my query that I used `ggplot`. But just to be sure, I tried again and does not work, unfortunately, even after using `scale_x_date` (which I had also done the first time). – Cat_Dog Jun 03 '21 at 03:22
  • @SukantoMukherjee What do you mean by does not work? What output do you get? What do you expect? What is the exact code that you used with `scale_x_date`? – Ronak Shah Jun 03 '21 at 03:30
  • I mean what I say. I simply expect the dates to shows up on the x-axis as they are in the column, which they don't. Also, please try and not be rude here when you respond everytime. I've spent the better part of two days trying to get this right and also trying to follow the guidelines here so a little patience will be appreciated. Here's the code: `ggplot(by_date, aes(Date, sales)) + scale_x_date(date_labels = "%d/%m/%y") + geom_line()`. This merely displays the dates as the first of every month like '01/01/10' and so on. – Cat_Dog Jun 03 '21 at 03:40
  • Sorry, if that sounded rude. I am trying to understand your expectation here. You can use `scale_x_date` as `scale_x_date(breaks = '1 month')`. Instead of 1 month you can use 6 month, 1 year or any other break that you want. To display all the dates in your data on x-axis change the dates to factor. `by_date$Date <- factor(by_date$Date)` and use `ggplot(by_date, aes(Date, sales, group = 1)) + geom_line()`. – Ronak Shah Jun 03 '21 at 03:49
  • Thanks, looks like this finally gets me the desired output. Appreciate the help. – Cat_Dog Jun 03 '21 at 04:01