3.Implement an R function to generate a line graph depicting the trend of a time-series dataset with seperate lines for each group,utilizing ggplot2’s group aesthetic .
Step1:Load the required libraries
library(ggplot2)library(tidyverse)
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr 1.1.4 ✔ readr 2.1.5
✔ forcats 1.0.0 ✔ stringr 1.5.1
✔ lubridate 1.9.4 ✔ tibble 3.2.1
✔ purrr 1.0.4 ✔ tidyr 1.3.1
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag() masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(tidyr)
Step2:Load the Built-in AirPassangers 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)
Step 3: Define a Function for Time-Series Line Graph
# Function to plot time-series trendplot_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) +# Line graphgeom_point(size =2) +# Add points for claritylabs(title = title,x ="Year",y ="Number of Passengers",color ="Year") +# Legend titletheme_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.