How to implement the facet grid feature using the

2019-08-16 16:58发布

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?

1条回答
Ridiculous、
2楼-- · 2019-08-16 17:33

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

查看更多
登录 后发表回答