Implement an R function to generate a line graph depicting the trend of a time seriser data-set, with seperate lines for each group, utilizing ggplot2’s group aesthetic.
Introduction
The document demonstrates how to create a time series line graph using the built in airpassengers data set in R. - the data set contains montly airline passanger counts from 1949 to 1960. we will convert the time series object into a data frame. ( because ggplot2works best with dataframes). - we will visualize passenger trends overtime using ggplot2 - we will draw seperate line for each year using group aesthetic ( and color for easy comparision).
Step 1 : load necessary libraries
we load :
ggplot2 to create the line plot.
dplyr for optional data handling(filtering , summerising etc).
tidyr for optional reshaping (not stricly reqired 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 data frame.
why convert?
airpassengers is a time-series (ts) object,dataframe. ggplot2 expects the data in a tabular structure ,where:
-each row is one observation. -each column is one variable.
so we build a dataframe with: -data:the sequence of monthly dates from 1949 - 01 2 1960-12 -passengers : the numerical values from the time-series. -year : Extracted from the date,used as the groups variable (factor).
#Create a monthly data sequence that matches a airpassengers lengthdata_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 = data_seq,passengers =as.numeric(AirPassengers),year=as.factor(format(data_seq,"%Y")))#Display first few rows head(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.