Nama: Farhah Lailatul Azizah

NIM: G5401231005

library(ggplot2)
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.2.1     ✔ readr     2.2.0
## ✔ forcats   1.0.1     ✔ stringr   1.6.0
## ✔ lubridate 1.9.5     ✔ tibble    3.3.1
## ✔ purrr     1.2.2     ✔ tidyr     1.3.2
## ── 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(dplyr)
library(scales)
## 
## Attaching package: 'scales'
## 
## The following object is masked from 'package:purrr':
## 
##     discard
## 
## The following object is masked from 'package:readr':
## 
##     col_factor

1. Comparison — mpg

Calculate the averagecty for each manufacturer, select the top 10, create a comparison plot, and summarize the main finding.

data("mpg")

# Calculate average cty for each manufacturer
mpg_summary <- mpg %>%
  group_by(manufacturer) %>%
  summarise(
    average_cty = mean(cty, na.rm = TRUE),
    .groups = "drop"
  ) %>%
  arrange(desc(average_cty))

top10_mpg <- mpg_summary %>%
  slice_max(order_by = average_cty, n = 10)

top10_mpg
## # A tibble: 10 × 2
##    manufacturer average_cty
##    <chr>              <dbl>
##  1 honda               24.4
##  2 volkswagen          20.9
##  3 subaru              19.3
##  4 hyundai             18.6
##  5 toyota              18.5
##  6 nissan              18.1
##  7 audi                17.6
##  8 pontiac             17  
##  9 chevrolet           15  
## 10 ford                14
ggplot(
  top10_mpg,
  aes(
    x = reorder(manufacturer, average_cty),
    y = average_cty
  )
) +
  geom_col(fill = "blue", width = 0.8) +
  geom_text(
    aes(label = round(average_cty, 1)),
    hjust = -0.1,
    size = 3.5
  ) +
  coord_flip() +
  labs(
    title = "Top 10 Manufacturers by Average City MPG",
    subtitle = "Based on average cty from the mpg dataset",
    x = "Manufacturer",
    y = "Average City MPG (cty)"
  ) +
  theme_minimal() +
  theme(
    plot.title = element_text(face = "bold"),
    axis.text = element_text(size = 10)
  )

Interpretation:

The bar chart shows the 10 manufacturers with the highest average city fuel economy. Manufacturers at the top of the ranking have higher average cty values, indicating better city fuel efficiency. The differences between manufacturers suggest that fuel economy varies considerably across vehicle manufacturers.

2. Distribution — diamonds

Choose one numerical variable, compare its distribution across one categorical variable, improve the plot appearance, and interpret the pattern.

# Load diamonds dataset
data("diamonds")

# Check the structure of the dataset
head(diamonds)
## # A tibble: 6 × 10
##   carat cut       color clarity depth table price     x     y     z
##   <dbl> <ord>     <ord> <ord>   <dbl> <dbl> <int> <dbl> <dbl> <dbl>
## 1  0.23 Ideal     E     SI2      61.5    55   326  3.95  3.98  2.43
## 2  0.21 Premium   E     SI1      59.8    61   326  3.89  3.84  2.31
## 3  0.23 Good      E     VS1      56.9    65   327  4.05  4.07  2.31
## 4  0.29 Premium   I     VS2      62.4    58   334  4.2   4.23  2.63
## 5  0.31 Good      J     SI2      63.3    58   335  4.34  4.35  2.75
## 6  0.24 Very Good J     VVS2     62.8    57   336  3.94  3.96  2.48
ggplot(
  diamonds,
  aes(
    x = cut,
    y = price,
    fill = cut
  )
) +
  geom_boxplot(alpha = 0.8) +
  labs(
    title = "Distribution of Diamond Prices by Cut",
    subtitle = "Price comparison across different cut categories",
    x = "Cut Quality",
    y = "Price (USD)"
  ) +
  theme_minimal() +
  theme(
    plot.title = element_text(face = "bold"),
    legend.position = "none"
  )

Interpretation:

The distribution of diamond prices differs across cut categories. The boxplot shows that diamond prices have a wide spread within each category and contain several high-price observations. The distributions are also strongly right-skewed, meaning that most diamonds have relatively lower prices while a smaller number of diamonds have very high prices.

3. Relationship — diamonds_sample

Visualize the relationship between carat and price, add at least one relevant aesthetic, customize the plot, and explain the relationship shown.

set.seed(123)

diamonds_sample <- diamonds %>%
  slice_sample(n = 1000)

head(diamonds_sample)
## # A tibble: 6 × 10
##   carat cut   color clarity depth table price     x     y     z
##   <dbl> <ord> <ord> <ord>   <dbl> <dbl> <int> <dbl> <dbl> <dbl>
## 1  0.73 Ideal I     VS1      60.7    56  2397  5.85  5.81  3.54
## 2  0.7  Ideal G     VS1      60.8    56  3300  5.73  5.8   3.51
## 3  0.31 Ideal D     VS1      61.6    55   713  4.3   4.33  2.66
## 4  0.31 Ideal H     VVS1     62.2    56   707  4.34  4.37  2.71
## 5  0.31 Ideal E     IF       60.9    55   987  4.39  4.41  2.68
## 6  0.83 Good  E     SI1      63.7    59  3250  5.95  5.89  3.77
ggplot(
  diamonds_sample,
  aes(
    x = carat,
    y = price,
    color = cut
  )
) +
  geom_point(
    alpha = 0.5,
    size = 2
  ) +
  geom_smooth(
    aes(group = 1),
    method = "lm",
    se = FALSE,
    color = "black",
    linewidth = 1
  ) +
  labs(
    title = "Relationship Between Carat and Diamond Price",
    subtitle = "Scatter plot with a linear trend line",
    x = "Carat",
    y = "Price (USD)",
    color = "Cut"
  ) +
  theme_minimal() +
  theme(
    plot.title = element_text(face = "bold"),
    legend.position = "right"
  )
## `geom_smooth()` using formula = 'y ~ x'

Interpretation:

The scatter plot shows a positive relationship between carat and price. As carat increases, diamond price generally tends to increase. However, the relationship is not perfectly linear because diamonds with similar carat sizes can have substantially different prices. The cut categories also show variation in the distribution of prices.

4. Time Series — economics

Visualize psavert over time, use clear labels and a suitable theme, highlight or annotate noticeable change, and provide a short interpretation.

data("economics")

head(economics)
## # A tibble: 6 × 6
##   date         pce    pop psavert uempmed unemploy
##   <date>     <dbl>  <dbl>   <dbl>   <dbl>    <dbl>
## 1 1967-07-01  507. 198712    12.6     4.5     2944
## 2 1967-08-01  510. 198911    12.6     4.7     2945
## 3 1967-09-01  516. 199113    11.9     4.6     2958
## 4 1967-10-01  512. 199311    12.9     4.9     3143
## 5 1967-11-01  517. 199498    12.8     4.7     3066
## 6 1967-12-01  525. 199657    11.8     4.8     3018
max_psavert <- economics %>%
  slice_max(psavert, n = 1)

max_psavert
## # A tibble: 1 × 6
##   date         pce    pop psavert uempmed unemploy
##   <date>     <dbl>  <dbl>   <dbl>   <dbl>    <dbl>
## 1 1975-05-01 1019. 215523    17.3     9.4     8433
ggplot(
  economics,
  aes(
    x = date,
    y = psavert
  )
) +
  geom_line(
    color = "steelblue",
    linewidth = 1
  ) +
  geom_point(
    data = economics %>%
      filter(psavert == max(psavert)),
    color = "red",
    size = 3
  ) +
  geom_text(
    data = max_psavert,
    aes(
      label = paste0(
        "Highest: ",
        round(psavert, 1),
        "%"
      )
    ),
    vjust = -1,
    color = "red"
  ) +
  scale_x_date(
    date_breaks = "5 years",
    date_labels = "%Y"
  ) +
  scale_y_continuous(
    limits = c(0, 20)
  ) +
  labs(
    title = "Personal Saving Rate Over Time",
    subtitle = "Monthly personal saving rate with the highest value highlighted",
    x = "Date",
    y = "Personal Saving Rate (%)"
  ) +
  theme_minimal() +
  theme(
    plot.title = element_text(face = "bold"),
    axis.text.x = element_text(angle = 45, hjust = 1)
  )

Interpretation:

The time-series plot shows that the personal saving rate changes substantially over time. The saving rate fluctuates throughout the period, with several noticeable increases and decreases. The highlighted point represents the highest observed saving rate in the dataset. Overall, the pattern indicates that personal saving behavior changes over time rather than remaining constant.

5. Improve a Visualization

#Original

ggplot(
  mpg,
  aes(
    x = class,
    y = hwy
  )
) +
  geom_boxplot()

#Improved

ggplot(
  mpg,
  aes(
    x = reorder(class, hwy, FUN = median),
    y = hwy
  )
) +
  geom_boxplot(
    fill = "steelblue",
    alpha = 0.8
  ) +
  coord_flip() +
  labs(
    title = "Highway Fuel Economy by Vehicle Class",
    subtitle = "Comparison of highway fuel economy across vehicle classes",
    x = "Vehicle Class",
    y = "Highway Fuel Economy (MPG)"
  ) +
  theme_minimal() +
  theme(
    plot.title = element_text(
      face = "bold",
      size = 16
    ),
    plot.subtitle = element_text(
      size = 11
    ),
    axis.title = element_text(
      face = "bold"
    )
  )

Interpretation:

The visualization was improved by adding a descriptive title, subtitle, clearer axis labels, a consistent color, and a minimal theme. The vehicle classes were reordered based on their median highway fuel economy, while coord_flip() was used to make the category labels easier to read. The improved boxplot allows us to compare the median, spread, and potential outliers of highway fuel economy across vehicle classes. Overall, smaller vehicle classes tend to have higher highway fuel economy, whereas larger vehicle classes generally have lower highway fuel economy.