To use autoplot with tsibble objects, you'll need to work within the tidyverts ecosystem, which includes packages like tsibble, fable, and feasts. These packages are designed for modern time series analysis in R and integrate seamlessly with ggplot2 and autoplot. Below is a step-by-step example of how to use autoplot with a tsibble object, including creating a tsibble, visualizing it, and optionally adding forecasts.
Step 1: Install and Load Required Packages
You'll need the tsibble package to create and manipulate time series data in a tidy format, and optionally fable for forecasting and feasts for time series features. Install them if you haven't already:
# Install required packages
install.packages(c("tsibble", "fable", "feasts", "ggplot2"))
# Load the packages
library(tsibble)
library(fable)
library(feasts)
library(ggplot2)
Step 2: Create or Convert Data to a tsibble
A tsibble is a time series data structure that requires a time index and optionally key variables. You can either create a tsibble from scratch or convert an existing time series (like AirPassengers) into a tsibble.
Example: Convert AirPassengers to a tsibble
The AirPassengers dataset is a built-in ts object. You can convert it to a tsibble using the as_tsibble function:
# Load the AirPassengers dataset
data("AirPassengers")
# Convert to a tsibble
air_tsibble <- as_tsibble(AirPassengers)
# View the tsibble
print(air_tsibble)
The output will look something like this:
# A tsibble: 144 x 2 [1M]
index value
<mth> <dbl>
1 1949 Jan 112
2 1949 Feb 118
3 1949 Mar 132
4 1949 Apr 129
5 1949 May 121
...
Here, index is the time index (monthly), and value is the number of passengers.
Step 3: Plot the tsibble Using autoplot
Now that you have a tsibble, you can use autoplot to create a time series plot. The autoplot function is extended by tsibble and feasts to work seamlessly with objects.