Unveiling the Time Traveler: Plotting Time Series in R
rtip
timeseries
Author
Steven P. Sanderson II, MPH
Published
December 28, 2023
Introduction
Ready to journey through time with R? Buckle up, because we’re about to explore the art of visualizing time-dependent data, known as time series analysis. Whether you’re tracking monthly sales patterns or analyzing yearly climate trends, R has your back with powerful tools to visualize these stories through time.
Our Flight Plan:
Loading Up with Data: Grabbing our trusty dataset, AirPassengers.
Taking Off with Base R: Creating a basic time series plot using base R functions.
Soaring with ggplot2: Crafting a visually stunning time series plot using the ggplot2 library.
Navigating Date Formatting: Customizing axis labels with scale_x_date() for clarity.
Landing with Your Own Exploration: Encouraging you to take the controls and create your own time series plots!
1. Ready for Takeoff: Loading Data
We’ll start by loading the built-in AirPassengers dataset, which chronicles monthly passenger totals from 1949 to 1960:
Base R offers a direct path to creating a time series plot:
plot(AirPassengers)
This generates a basic line plot, revealing an upward trend in air passengers over time.
3. ggplot2: The High-Flying, Visually Staggering Journey
For more customization and visual appeal, we’ll turn to the ggplot2 library and the healthyR.ts library to first convert the AirPassengers Data set into a tibble:
library(ggplot2)library(dplyr)library(healthyR.ts)df <-ts_to_tbl(AirPassengers)ggplot(df, aes(x = date_col, y = value)) +geom_line() +theme_minimal() +labs(title ="Monthly Air Passengers (1949-1960)",x ="Year",y ="Passengers")
This creates a more refined plot with informative labels and a sleeker aesthetic.
4. Mastering Time with scale_x_date()
To fine-tune the x-axis date labels, ggplot2 offers the versatile scale_x_date() function. Let’s display years and abbreviated months:
ggplot(df, aes(x = date_col, y = value)) +geom_line() +theme_minimal() +scale_x_date(date_labels ="%b %Y") +labs(title ="Monthly Air Passengers (1949-1960)",y ="Passengers")
5. Your Turn to Pilot: Experiment and Explore!
R is your playground for time series visualization! Try these challenges:
Explore other time series datasets in R.
Customize plots further with colors, themes, and annotations.
Use scale_x_date() to display different date formats.
Combine multiple time series in a single plot.
Unleash your creativity and uncover the captivating stories hidden within time series data! For a start here are some resources: