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(tidyr)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(ggplot2)
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.
#convert time-series data to a dataframeAirPassengers
plot_time_series<-function(data, x_col, y_col, group_col, title="Air Passenger Trends" ){ggplot(data, aes_string(x=x_col,y= y_col , color = group_col,group = group_col))+geom_line(size =1.2)+geom_point(size =2)+labs(title = title,x="year",y="number of passengers",color ="year") +theme_minimal()+theme(legend.position ="top")}#call the functionplot_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.