Implement an R function to generate a line graph depicting the trend of a time-series dataset, with separate lines for each group, utilizing ggplot2’s group aesthetic.
Introduction
This document demonstrates how to create a time-series line graph using the built-in AirPassengers dataset in R.
The dataset contains monthly airline passenger counts from 1949 to 1960. We will use ggplot2 to visualize trends, with separate lines for each year.
Step 1: Load necessary libraries
library(ggplot2)
Warning: package 'ggplot2' was built under R version 4.1.3
library(dplyr)
Warning: package 'dplyr' was built under R version 4.1.3
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)
Warning: package 'tidyr' was built under R version 4.1.3
Step 2Load the Built-in AirPassengers Dataset
The AirPassengers dataset is a time series object in R.
We first convert it into a dataframe to use it with ggplot2.
Date: Represents the month and year (from January 1949 to December 1960).
Passengers: Monthly airline passenger counts.
Year: Extracted year from the date column, which will be used to group the data.
# Convert time-series data to a dataframedata <-data.frame(Date =seq(as.Date("1949-01-01"), by ="month", length.out =length(AirPassengers)),Passengers =as.numeric(AirPassengers),Year =as.factor(format(seq(as.Date("1949-01-01"), by ="month", length.out =length(AirPassengers)), "%Y")))# Display first few rowshead(data, n=20)