0

I am using RStudio and I have a time series data (ts object) called data1.

Here is how data1 looks:

     Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
2014 135 172 179 189 212  47 301 183 247 292 280 325
2015 471 243 386 235 388 257 344 526 363 261 189 173
2016 272 267 197 217 393 299 343 341 315 305 384 497

To plot the above, I have run this code:

plot (data1)

and I get the following plot:

figure 1

I want to have a plot that is broken by Year and I was thinking of implementing the facet_grid feature found in ggplot2 but since my data is a ts object, I can't use ggplot2 directly on it.

After some research, I've found that the ggfortify library works with ts objects. However, I am having a hard time trying to figure out to use the facet_grid feature with it.

My aim to is to plot something like below from my ts data:

figure 2

'Female'and 'Male' will be replaced by the Years 2014, 2015 and 2016. The X-axis will be the Months (Jan, Feb, Mar, and so on) and the y-axis will be the values in the ts file . I would prefer a line plot rather than a dot plot.

Am I on the right track here or is there another way of approaching this problem?

user3115933
  • 4,303
  • 15
  • 54
  • 94
  • There are many examples on SO how to `reshape` your data and plot facets with `ggplot2`. PS: In your case I would use `geom_line(aes(color = factor(year)))` instead of facets. – pogibas Jan 02 '18 at 10:32
  • I know I can reshape my data and use ggplot2. My point here is whether I can do it without reshaping the data and make use of ggfortify. – user3115933 Jan 02 '18 at 10:43
  • Anyone who gave minus marks did not understand the purpose of my question. I think it is clear in the title of the question that I am looking for a solution on how to make this work on a ts file. It's not about reshaping the data. – user3115933 Jan 02 '18 at 10:51
  • 2
    Have a look at `?ggplot2::autoplot`. You might try `library(lubridate); autoplot(data1) + facet_grid(. ~ year(Index), scales = "free_x")` – markus Jan 02 '18 at 11:04
  • @markus Thanks. Exactly what I was looking for! Please post as an answer and I'll give my vote. – user3115933 Jan 02 '18 at 11:26

1 Answers1

2

We can use ggplot2::autoplot. I will use AirPassengers data as an example.

library(ggplot2)
library(lubridate)
autoplot(AirPassengers) + 
 facet_grid(. ~ year(Index), scales = "free_x") + 
 scale_x_date(date_labels = "%b")

enter image description here

markus
  • 25,843
  • 5
  • 39
  • 58