0

I would like to know if the order of dates matter when plotting a time series in R.

For example, the dataframe below has it's date starting from the year 2010 onwards increasing as it goes down, for example till 2011:

Date         Number of visits

2010-05-17    13
2010-05-18    11
2010-05-19     4
2010-05-20     2
2010-05-21    23
2010-05-22    26
2011-05-13    14

and below where the year are jumbled up.

Date         Number of visits

2011-06-19   10
2009-04-25   5
2012-03-09   20
2011-01-04   45

Would i be able to plot a time series in R for the second example above? Is it required that in order to plot a time series, the dates must be sorted?

Maxxx
  • 3,688
  • 6
  • 28
  • 55
  • Please check this [post](https://stackoverflow.com/questions/4843969/plotting-time-series-with-date-labels-on-x-axis) - main idea is to *Since the times are dates be sure to use "Date" class, not "POSIXct" or "POSIXlt"* – pogibas Apr 13 '19 at 10:40
  • @PoGibas why not make it into an answer? – Roman Luštrik Apr 13 '19 at 10:41
  • @RomanLuštrik Isn't this a duplicate? I just wanted to make sure that OP understands the problem – pogibas Apr 13 '19 at 10:42
  • While the answer is similar or the same, I think the question about order of dates in a data.frame is different and valid. – Roman Luštrik Apr 13 '19 at 10:44

2 Answers2

0

Assuming the data shown reproducibly int he Note at the end create an ordering vector o and then plot the ordered data:

o <- order(dat$Date)
plot(dat[o, ], type = "o")

or convert the data to a zoo series, which will automatically order it, and then plot.

library(zoo)
z <- read.zoo(dat)
plot(z, type = "o")

Note

The data in reproducible form:

Lines <- "Date         Number of visits
2010-05-17    13
2010-05-18    11
2010-05-19     4
2010-05-20     2
2010-05-21    23
2010-05-22    26
2011-05-13    14"
dat <- read.csv(text = gsub("  +", ",", readLines(textConnection(Lines))),
 check.names = FALSE)
dat$Date <- as.Date(dat$Date)
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
0

as.Date slove your problem:

data$Date <- as.Date(x$Date)
ggplot(data, aes(Date, Number_of_visits)) + geom_line()

enter image description here

Iman
  • 2,224
  • 15
  • 35