Yohanes Deo Pringgondani_G5401231051_Practicum Exercise 3

Yohanes Deo Pringgondani - G5401231051 - Exercise P3

Preparation

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
library(ggplot2)
Warning: package 'ggplot2' was built under R version 4.4.3

Comparison - mpg

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

Calculate the average cty for each manufacturer and select the top 10 manufacturers based on their average cty

top10_mpg <- mpg |> 
  group_by(manufacturer) |> 
  summarise(avg_cty = mean(cty)) |> 
  arrange(desc(avg_cty)) |> 
  slice_head(n = 10)

top10_mpg
# A tibble: 10 × 2
   manufacturer avg_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  

The initial comparison plot displays the average city MPG for the top 10 manufacturers. However, the plot uses default formatting, making the visualization less visually refined.

ggplot(
  top10_mpg,
  aes(
    x=manufacturer,
    y=avg_cty
  )
) +
  geom_col()

The plot was customized by adding a descriptive title, axis labels, value labels, a consistent color, and a minimal theme. The manufacturers were also ordered from the highest to the lowest average city MPG, making the comparison easier to interpret.

ggplot(
  top10_mpg,
  aes(
    x=reorder(manufacturer,-avg_cty),
    y=avg_cty
  )
) +
  geom_col(fill = "#2C7FB8") +
  geom_text(
    aes(label = round(avg_cty,1)),
    vjust = -0.5
  ) +
  labs(
    title = "Top 10 Manufacturers by Average City MPG",
    x = "Manufacturer",
    y = "Average City MPG"
  ) +
  theme_minimal() +
  theme(
    plot.title = element_text(face = "bold", size = 16),
    axis.title = element_text(size = 11),
    axis.text = element_text(size = 10)
  )

From the plot, Honda has the highest average city MPG (24.4), while Ford has the lowest (14.0) among the top 10 manufacturers. The results show a difference of 10.4 MPG between the highest and lowest averages.

Distribution - diamonds

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

The initial boxplot compares the distribution of diamond prices across different cut categories using the default ggplot2 appearance.

ggplot(
  diamonds,
  aes(
    x=cut,
    y=price
  )
) +
  geom_boxplot()

The plot was improved by applying a categorical color palette, adding a descriptive title and axis labels, and using a minimal theme with clearer typography. The legend was removed because the categories are already displayed on the x-axis.

ggplot(
  diamonds,
  aes(
    x=cut,
    y=price,
    fill=cut
  )
) +
  geom_boxplot() +
  scale_fill_brewer(palette = "Set2") +
  labs(
    title = "Diamond Price Distribution by Cut",
    x = "Cut Quality",
    y = "Price"
  ) +
  theme_minimal() +
  theme(
    plot.title = element_text(face = "bold", size = 16),
    axis.title = element_text(size = 11),
    axis.text = element_text(size = 10),
    legend.position = "none"
  )

The distribution of diamond prices varies across cut categories. Premium diamonds show a relatively high median price and a wide interquartile range, while Ideal diamonds have a relatively lower median price. However, the distributions overlap substantially across categories, indicating that cut alone does not completely explain differences in diamond prices.

A violin plot was also used to complement the boxplot by providing a clearer view of the shape and density of the price distribution across different cut categories.

ggplot(
  diamonds,
  aes(
    x=cut,
    y=price,
    fill=cut
  )
) +
  geom_violin() +
  scale_fill_brewer(palette = "Set2") +
  labs(
    title = "Diamond Price Distribution by Cut",
    x = "Cut Quality",
    y = "Price"
  ) +
  theme_minimal() +
  theme(
    plot.title = element_text(face = "bold", size = 16),
    axis.title = element_text(size = 11),
    axis.text = element_text(size = 10),
    legend.position = "none"
  )

The violin plots show that diamond prices are highly concentrated at lower price ranges across all cut categories, with long tails extending toward higher prices. The distributions overlap substantially, although their shapes and spread vary across cut categories.

The plot was improved by combining a violin plot with a boxplot. The violin plot shows the shape and density of the price distribution, while the boxplot highlights the median and quartiles. A categorical color palette, descriptive labels, and a minimal theme were also added to improve readability.

ggplot(
  diamonds,
  aes(
    x = cut,
    y = price,
    fill = cut
  )
) +
  geom_violin() +
  geom_boxplot(
    width = 0.15,
    fill = "white"
  ) +
  scale_fill_brewer(palette = "Set2") +
  labs(
    title = "Diamond Price Distribution by Cut",
    x = "Cut Quality",
    y = "Price"
  ) +
  theme_minimal() +
  theme(
    plot.title = element_text(face = "bold", size = 16),
    axis.title = element_text(size = 11),
    axis.text = element_text(size = 10),
    legend.position = "none"
  )

Diamond prices are concentrated at lower price ranges across all cut categories, with long tails extending toward higher prices. The distributions overlap considerably, although their shapes, medians, and spreads vary across cut categories.

Relationship - diamonds_sample

Visualize the relationship between carat and price, add at least one relevant aesthetic, apply suitable customization, and explain the relationship shown.

A random sample of 1,000 observations was selected from the diamonds dataset to create diamonds_sample. The set.seed(123) function was used to ensure that the same sample could be reproduced.

set.seed(123)

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

The initial scatter plot was created to visualize the relationship between carat and price. The plot shows a clear positive relationship, where diamonds with larger carat sizes generally have higher prices. However, the points are displayed in a single color, making it difficult to examine the role of diamond cut in this relationship.

ggplot(
  diamonds_sample,
  aes(
    x=carat,
    y=price,
  )
) +
  geom_point()

The scatter plot was then customized by mapping color to the cut variable and applying transparency to the points. Different colors represent different cut categories, while transparency helps reduce the visual effect of overlapping points. A descriptive title, axis labels, and a minimal theme were also added to improve readability.

ggplot(
  diamonds_sample,
  aes(
    x=carat,
    y=price,
    color=cut
  )
) + 
  geom_point(alpha = 0.5) +
  geom_smooth(
    aes(group = 1),
    se = FALSE, 
    color = "black"
    ) +
  labs(
    title = "Relationship Between Carat and Price",
    x = "Carat",
    y = "Price",
    color = "Cut Quality"
  ) +
  theme_minimal() +
  theme(
    plot.title = element_text(face = "bold", size = 16),
    axis.title = element_text(size = 11),
    axis.text = element_text(size = 10)
  )
`geom_smooth()` using method = 'gam' and formula = 'y ~ s(x, bs = "cs")'

To make the comparison across cut categories clearer, the scatter plot was divided into separate panels using facet_wrap(~cut). This allows the relationship between carat and price to be examined individually for Fair, Good, Very Good, Premium, and Ideal diamonds.

ggplot(
  diamonds_sample,
  aes(
    x = carat,
    y = price,
    color = cut
  )
) +
  geom_point(alpha = 0.5) +
  facet_wrap(~cut) +
  geom_smooth(
    aes(group = 1),
    se = FALSE,
    color = "black"
  ) +
  labs(
    title = "Relationship Between Carat and Price by Cut",
    x = "Carat",
    y = "Price",
    color = "Cut Quality"
  ) +
  theme_minimal() +
  theme(
    plot.title = element_text(face = "bold", size = 16),
    axis.title = element_text(size = 11),
    axis.text = element_text(size = 10),
    legend.position = "none"
  )
`geom_smooth()` using method = 'loess' and formula = 'y ~ x'

Overall, the visualization shows a positive but nonlinear relationship between carat and price. As carat increases, price generally increases, but the rate of increase becomes greater at higher carat values. This pattern can also be observed across the different cut categories in the faceted plot.

Time Series - economics

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

The basic line chart shows the personal saving rate over time, with date on the x-axis and psavert on the y-axis. The overall pattern suggests a general decline in the personal saving rate over the observed period, although the series fluctuates considerably from month to month.

ggplot(
  economics,
  aes(
    x=date,
    y=psavert
  )
) +
  geom_line()

To provide more context, the highest and lowest personal saving rates were identified and highlighted on the plot. The highest saving rate occurred in the mid-1970s, while the lowest saving rate occurred in the mid-2000s. These points make the extreme values easier to identify and provide a clearer view of the range of the saving rate over time.

lowest_psavert <- economics %>%
  slice_min(psavert, n = 1)

highest_psavert <- economics %>%
  slice_max(psavert, n = 1)
ggplot(
  economics,
  aes(
    x = date,
    y = psavert
  )
) +
  geom_line() +
  
  geom_point(
    data = lowest_psavert,
    aes(x = date, y = psavert),
    color = "#E45756",
    size = 3
  ) +
  geom_text(
    data = lowest_psavert,
    aes(
      x = date,
      y = psavert,
      label = "Lowest saving rate"
    ),
    vjust = 1.4,
    color = "#E45756",
    fontface = "bold"
  ) +
  
  geom_point(
    data = highest_psavert,
    aes(x = date, y = psavert),
    color = "#2C7FB8",
    size = 3
  ) +
  geom_text(
    data = highest_psavert,
    aes(
      x = date,
      y = psavert,
      label = "Highest saving rate"
    ),
    vjust = -1,
    color = "#2C7FB8",
    fontface = "bold"
  ) +
  
  scale_y_continuous(
    expand = expansion(mult = c(0.10, 0.15))
  ) +
  
  labs(
    title = "Personal Saving Rate Over Time",
    x = "Year",
    y = "Personal Saving Rate (%)"
  ) +
  theme_minimal() +
  theme(
    plot.title = element_text(face = "bold", size = 16),
    axis.title = element_text(size = 11),
    axis.text = element_text(size = 10)
  )

To identify noticeable changes in the series, the month-to-month change in the personal saving rate was calculated using the lag() function. The largest decrease was identified as 5.7 percentage points, while the largest increase was 4.4 percentage points.

change_psavert <- economics %>%
  mutate(
    change = psavert - lag(psavert)
  )

change_psavert %>%
  slice_min(change, n = 1)
# A tibble: 1 × 7
  date          pce     pop psavert uempmed unemploy change
  <date>      <dbl>   <dbl>   <dbl>   <dbl>    <dbl>  <dbl>
1 2013-01-01 11203. 315390.     6.3    15.8    12471   -5.7
change_psavert %>%
  slice_max(change, n = 1)
# A tibble: 1 × 7
  date          pce    pop psavert uempmed unemploy change
  <date>      <dbl>  <dbl>   <dbl>   <dbl>    <dbl>  <dbl>
1 2008-05-01 10054. 304323     7.8     7.9     8395    4.4
ggplot(
  economics,
  aes(
    x = date,
    y = psavert
  )
) +
  geom_line() +
  
  geom_point(
    data = lowest_psavert,
    aes(x = date, y = psavert),
    color = "#E45756",
    size = 3
  ) +
  geom_text(
    data = lowest_psavert,
    aes(
      x = date,
      y = psavert,
      label = "Lowest saving rate"
    ),
    vjust = 1.8,
    color = "#E45756",
    fontface = "bold",
    size = 3.5
  ) +
  
  geom_point(
    data = highest_psavert,
    aes(x = date, y = psavert),
    color = "#2C7FB8",
    size = 3
  ) +
  geom_text(
    data = highest_psavert,
    aes(
      x = date,
      y = psavert,
      label = "Highest saving rate"
    ),
    vjust = -1.2,
    color = "#2C7FB8",
    fontface = "bold",
    size = 3.5
  ) +
  
  geom_vline(
    xintercept = as.Date("2008-05-01"),
    linetype = "dashed",
    color = "#2C7FB8"
  ) +
  annotate(
    "text",
    x = as.Date("2008-05-01"),
    y = 14,
    label = "Largest increase\n(+4.4%)",
    color = "#2C7FB8",
    size = 3,
    fontface = "bold",
    hjust = 1
  ) +
  
  geom_vline(
    xintercept = as.Date("2013-01-01"),
    linetype = "dashed",
    color = "#E45756"
  ) +
  annotate(
    "text",
    x = as.Date("2013-01-01"),
    y = 14,
    label = "Largest decrease\n(-5.7%)",
    color = "#E45756",
    size = 3,
    fontface = "bold",
    hjust = 0
  ) +
  
  scale_y_continuous(
    expand = expansion(mult = c(0.10, 0.15))
  ) +
  
  scale_x_date(
    expand = expansion(mult = c(0.02, 0.20))
  ) +
  
  labs(
    title = "Personal Saving Rate Over Time",
    x = "Year",
    y = "Personal Saving Rate (%)"
  ) +
  
  theme_minimal() +
  
  theme(
    plot.title = element_text(face = "bold", size = 16),
    axis.title = element_text(size = 11),
    axis.text = element_text(size = 10)
  )

The final chart combines these findings into a more informative time-series visualization. The highest and lowest saving rates are marked with colored points and labels, while dashed vertical lines indicate the dates with the largest increase and decrease. The annotations help draw attention to important changes without obscuring the underlying time series.

Improve a Visualization

Create one visualization with at least three presentation problems, then redesign it using improvements such as color, theme, scale, labels, legend, or annotation, and briefly explain the changes.

The initial visualization shows the relationship between engine displacement and highway fuel efficiency using a basic scatter plot. Each point represents a vehicle, with engine displacement on the x-axis and highway fuel efficiency on the y-axis. However, the plot does not distinguish between different vehicle classes, making it difficult to identify patterns across categories.

ggplot(
  mpg,
  aes(
    x = displ,
    y = hwy
  )
) +
  geom_point()

Color was added to distinguish vehicles based on their class. This makes it easier to identify differences between vehicle categories and observe how each class is distributed across engine size and highway fuel efficiency.

ggplot(
  mpg,
  aes(
    x = displ,
    y = hwy,
    color = class
  )
) +
  geom_point()

The point size and transparency were adjusted to improve the readability of the scatter plot. A moderate transparency level helps reduce visual overlap between points, while the slightly larger point size makes individual observations easier to see.

ggplot(
  mpg,
  aes(
    x = displ,
    y = hwy,
    color = class
  )
) +
  geom_point(
    alpha = 0.7,
    size = 2.5
  )

A linear trend line was added to highlight the overall relationship between engine displacement and highway fuel efficiency. The negative slope indicates that vehicles with larger engine displacement generally tend to have lower highway fuel efficiency.

ggplot(
  mpg,
  aes(
    x = displ,
    y = hwy,
    color = class
  )
) +
  geom_point(
    alpha = 0.7,
    size = 2.5
  ) +
  geom_smooth(
    aes(group = 1),
    method = "lm",
    se = FALSE,
    color = "black",
    linewidth = 1
  )
`geom_smooth()` using formula = 'y ~ x'

The plot was further improved by adding an informative title, subtitle, axis labels, and a clearer legend title. The minimal theme was also applied to create a cleaner appearance and improve the overall readability of the visualization.

ggplot(
  mpg,
  aes(
    x = displ,
    y = hwy,
    color = class
  )
) +
  geom_point(
    alpha = 0.7,
    size = 2.5
  ) +
  geom_smooth(
    aes(group = 1),
    method = "lm",
    se = FALSE,
    color = "black",
    linewidth = 1
  ) +
  labs(
    title = "Engine Size vs Highway Fuel Efficiency",
    subtitle = "Larger engines tend to have lower highway fuel efficiency",
    x = "Engine Displacement (L)",
    y = "Highway Fuel Efficiency (MPG)",
    color = "Vehicle Class"
  ) +
  theme_minimal()
`geom_smooth()` using formula = 'y ~ x'

Overall, the visualization was improved progressively from a basic scatter plot into a more informative and visually clear chart. Color helps distinguish vehicle classes, transparency improves the visibility of overlapping observations, the trend line highlights the overall relationship, and descriptive labels and a cleaner theme provide additional context for interpretation.