Quarto enables you to weave together content and executable code into a finished document. To learn more about Quarto see https://quarto.org.
Introduction
This document demonstrates how to create a time-series lines graph using the built-in AirPassengers dataset in R.
The dataset contains monthly airline passenger counts from 1949 to 1960.
We will convert the time-series object into a dataframe (because ggplot2 works best with dataframe).
We will visualize passenger trwnds over time using ggplot2.
We will draw separate lines for each year using group aesthetic (and color for easy comparison).
Step 1: Load necessary libraries
We load:
ggplot2 to create the line plot.
dplyr for optical data handling (filtering, summarising, etc).
tidyr for optional reshaping (not strictly required here, but commonly used in tidy workflows).
library(ggplot2)library(dplyr)
Attaching package: 'dplyr'
The following objects are masked from 'package:stats':
filter, lag
The following objects are masked from 'package:base':
intersect, setdiff, setequal, union
library(tidyr)
Step 2: Load the Built-in AirPassengers` Dataset and Convert It to a Dataframe
] ### Why Convert?
AirPassengers is a time-series (ts) object, not a dataframe.
ggplot2 expects data in a tabular structure, where:
each row is one observation
each column is one variable
So we build a dataframe with:
Data: a sequence of monthly dates from 1949-01 to 1960-12
Passengers: the numeric values from the time-series
Year: extracted from the date, used as the grouping variable (factor)
What This Code Is Doing (Line-by-Line)
seq(as.Date("1949-01-01"), by = "month", length.out = length(AirPassengers)) creates a monthly date sequence
# Create a monthly date sequence that matches AirPassengers lengthdate_seq <-seq(as.Date("1949-01-01"),by ="month",length.out =length(AirPassengers))# Convert the time-series object into a dataframe for ggplot2data <-data.frame(Date = date_seq,Passengers =as.numeric(AirPassengers),Year =as.factor(format(date_seq, "%Y")))# Display first few rowshead(data, n=20)
plot_time_series( data,"Date","Passengers","Year","Trend of Airline Passengers Over Time")
Warning: `aes_string()` was deprecated in ggplot2 3.0.0.
ℹ Please use tidy evaluation idioms with `aes()`.
ℹ See also `vignette("ggplot2-in-packages")` for more information.
Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
ℹ Please use `linewidth` instead.