#Task 1
#Load mtcars data set
data(mtcars)

#Display the rows
head(mtcars)
##                    mpg cyl disp  hp drat    wt  qsec vs am gear carb
## Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
## Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
## Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
## Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
## Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
## Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1
#Summary statistics of the data set
summary(mtcars)
##       mpg             cyl             disp             hp       
##  Min.   :10.40   Min.   :4.000   Min.   : 71.1   Min.   : 52.0  
##  1st Qu.:15.43   1st Qu.:4.000   1st Qu.:120.8   1st Qu.: 96.5  
##  Median :19.20   Median :6.000   Median :196.3   Median :123.0  
##  Mean   :20.09   Mean   :6.188   Mean   :230.7   Mean   :146.7  
##  3rd Qu.:22.80   3rd Qu.:8.000   3rd Qu.:326.0   3rd Qu.:180.0  
##  Max.   :33.90   Max.   :8.000   Max.   :472.0   Max.   :335.0  
##       drat             wt             qsec             vs        
##  Min.   :2.760   Min.   :1.513   Min.   :14.50   Min.   :0.0000  
##  1st Qu.:3.080   1st Qu.:2.581   1st Qu.:16.89   1st Qu.:0.0000  
##  Median :3.695   Median :3.325   Median :17.71   Median :0.0000  
##  Mean   :3.597   Mean   :3.217   Mean   :17.85   Mean   :0.4375  
##  3rd Qu.:3.920   3rd Qu.:3.610   3rd Qu.:18.90   3rd Qu.:1.0000  
##  Max.   :4.930   Max.   :5.424   Max.   :22.90   Max.   :1.0000  
##        am              gear            carb      
##  Min.   :0.0000   Min.   :3.000   Min.   :1.000  
##  1st Qu.:0.0000   1st Qu.:3.000   1st Qu.:2.000  
##  Median :0.0000   Median :4.000   Median :2.000  
##  Mean   :0.4062   Mean   :3.688   Mean   :2.812  
##  3rd Qu.:1.0000   3rd Qu.:4.000   3rd Qu.:4.000  
##  Max.   :1.0000   Max.   :5.000   Max.   :8.000
#Structure of the data set
str(mtcars)
## 'data.frame':    32 obs. of  11 variables:
##  $ mpg : num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
##  $ cyl : num  6 6 4 6 8 6 8 4 4 6 ...
##  $ disp: num  160 160 108 258 360 ...
##  $ hp  : num  110 110 93 110 175 105 245 62 95 123 ...
##  $ drat: num  3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...
##  $ wt  : num  2.62 2.88 2.32 3.21 3.44 ...
##  $ qsec: num  16.5 17 18.6 19.4 17 ...
##  $ vs  : num  0 0 1 1 0 1 0 1 1 1 ...
##  $ am  : num  1 1 1 0 0 0 0 0 0 0 ...
##  $ gear: num  4 4 4 3 3 3 3 4 4 4 ...
##  $ carb: num  4 4 1 1 2 1 4 2 2 4 ...
#Convert categorical variables to factors
mtcars$am <- factor(mtcars$am, labels = c("Automatic", "Manual"))
mtcars$vs <- factor(mtcars$vs, labels = c("V-shaped", "Straight"))
mtcars$cyl <- factor(mtcars$cyl)
mtcars$gear <- factor(mtcars$gear)
mtcars$carb <- factor(mtcars$carb)

#Add row names as a column for easier reference
mtcars$car_model <- rownames(mtcars)

#Display updated structure
str(mtcars)
## 'data.frame':    32 obs. of  12 variables:
##  $ mpg      : num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
##  $ cyl      : Factor w/ 3 levels "4","6","8": 2 2 1 2 3 2 3 1 1 2 ...
##  $ disp     : num  160 160 108 258 360 ...
##  $ hp       : num  110 110 93 110 175 105 245 62 95 123 ...
##  $ drat     : num  3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...
##  $ wt       : num  2.62 2.88 2.32 3.21 3.44 ...
##  $ qsec     : num  16.5 17 18.6 19.4 17 ...
##  $ vs       : Factor w/ 2 levels "V-shaped","Straight": 1 1 2 2 1 2 1 2 2 2 ...
##  $ am       : Factor w/ 2 levels "Automatic","Manual": 2 2 2 1 1 1 1 1 1 1 ...
##  $ gear     : Factor w/ 3 levels "3","4","5": 2 2 2 1 1 1 1 2 2 2 ...
##  $ carb     : Factor w/ 6 levels "1","2","3","4",..: 4 4 1 1 2 1 4 2 2 4 ...
##  $ car_model: chr  "Mazda RX4" "Mazda RX4 Wag" "Datsun 710" "Hornet 4 Drive" ...
#Task 2
# Load necessary libraries
library(ggplot2)
## Warning: package 'ggplot2' was built under R version 4.4.3
library(dplyr)
## Warning: package 'dplyr' was built under R version 4.4.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
#Create an enhanced scatter plot
ggplot(mtcars, aes(x = wt, y = mpg, color = am)) +
  
#Add points with varying size based on horsepower
  geom_point(aes(size = hp, shape = cyl), alpha = 0.7) +
  
#Add regression lines for each transmission type
  geom_smooth(method = "lm", se = TRUE, alpha = 0.2) +
  
#Add car model labels for selected cars
  geom_text(data = subset(mtcars, mpg > 30 | hp > 300 | wt > 5), 
            aes(label = car_model), 
            nudge_y = 0.5, 
            size = 3,
            check_overlap = TRUE) +
  
#Add labels and title
  labs(
    title = "Relationship between Weight and Fuel Efficiency in Cars",
    subtitle = "Point size represents horsepower, shape represents cylinders",
    x = "Weight (1000 lbs)",
    y = "Miles per Gallon",
    color = "Transmission",
    size = "Horsepower",
    shape = "Cylinders"
  ) +
  
#Custom theme
  theme_minimal() +
  
#Adjust color scale
  scale_color_brewer(palette = "Set1") +
  
#Add annotations
  annotate("text", x = 4, y = 32, label = "Lighter cars tend to have\nbetter fuel efficiency", 
           fontface = "italic", size = 3.5) +
  
#Set custom axis limits
  scale_y_continuous(limits = c(10, 35)) +
  
#Custom theme elements
  theme(
    legend.position = "right",
    plot.title = element_text(face = "bold"),
    plot.subtitle = element_text(face = "italic", size = 10)
  )
## `geom_smooth()` using formula = 'y ~ x'

#Task 3
#Load the plotly library
library(plotly)
## Warning: package 'plotly' was built under R version 4.4.3
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
#Create a scatter plot with hover information
fig <- plot_ly(
  data = mtcars,
  x = ~wt,                        
  y = ~mpg,
  color = ~factor(am, labels = c("Automatic", "Manual")),
  type = "scatter",
  mode = "markers",
  marker = list(size = 10),
  
#Hover text
  text = ~paste("Car:", rownames(mtcars), 
                "<br>MPG:", mpg, 
                "<br>Weight:", wt)
)

#Add title and axis labels
fig <- fig %>% layout(
  title = "Car Weight vs. Fuel Efficiency",
  xaxis = list(title = "Weight (1000 lbs)"),
  yaxis = list(title = "Miles Per Gallon"),
  legend = list(title = list(text = "Transmission"))
)

#Display the plot
fig
## Warning in RColorBrewer::brewer.pal(N, "Set2"): minimal value for n is 3, returning requested palette with 3 different levels
## Warning in RColorBrewer::brewer.pal(N, "Set2"): minimal value for n is 3, returning requested palette with 3 different levels
#Task 4
#load necessary libraries
library(gganimate)
## Warning: package 'gganimate' was built under R version 4.4.3
library(png)

#Prepare the data set with a time variable
mtcars_animated <- mtcars %>%
  mutate(car_model = rownames(.)) %>%
  
  # Convert categorical variables to factors
  mutate(
    am = factor(am, labels = c("Automatic", "Manual")),
    cyl = as.factor(cyl)
  ) %>%
  
  # Create a time variable
  arrange(mpg) %>%
  mutate(frame_id = 1:n())

#Create the animation
p <- ggplot(mtcars_animated, aes(x = wt, y = mpg, color = am)) +
  geom_point(aes(size = hp), alpha = 0.7) +
  geom_text(aes(label = car_model), hjust = -0.2, size = 3) +
  labs(
    title = "Car Efficiency Exploration",
    subtitle = "Frame {frame_along}",
    x = "Weight (1000 lbs)",
    y = "Miles per Gallon"
  ) +
  theme_minimal() +
  
#Use transition_reveal instead of transition_time for this type of sequence
  transition_reveal(frame_id) +
  ease_aes('linear')

#Render the animation
animate(p, nframes = 32, fps = 4, renderer = av_renderer())