INDEPENDENT EXCERCISE

Author

Emanuel Mlumba Kiula_M0501261803

suppressPackageStartupMessages({
  library(ggplot2)
  library(dplyr)
  library(scales)
})
Warning: package 'ggplot2' was built under R version 4.5.3
Warning: package 'dplyr' was built under R version 4.5.3
  1. Comparison mpg
# Average city mpg for each manufacturer
manufacturer_mpg <- mpg %>%
  group_by(manufacturer) %>%
  summarise(
    average_cty = mean(cty, na.rm = TRUE)
  ) %>%
  arrange(desc(average_cty))

# The top 10 manufacturers
top10_mpg <- manufacturer_mpg %>%
  slice_head(n = 10)

# The results
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  

Comparison plot

ggplot(top10_mpg,
       aes(x = reorder(manufacturer, average_cty),
           y = average_cty)) +
  geom_col() +
  coord_flip() +
  labs(
    title = "Top 10 Manufacturers by Average City Fuel Efficiency",
    x = "Manufacturer",
    y = "Average City MPG"
  ) +
  theme_minimal()

Interpretation

The plot compares the average city fuel efficiency across the top 10 manufacturers. Manufacturers positioned higher on the chart have higher average city MPG, indicating that their vehicles generally use less fuel to travel the same distance in city driving. The results show clear differences in fuel efficiency among manufacturers, suggesting that the typical city fuel economy varies considerably across brands. Overall, the chart makes it easy to identify manufacturers with relatively higher and lower average city fuel efficiency.

  1. Distribution - Diamonds
ggplot(diamonds,
       aes(x = cut, y = carat)) +
  geom_boxplot() +
  labs(
    title = "Distribution of Diamond Carat Across Cut Categories",
    x = "Cut Quality",
    y = "Diamond Weight"
  ) +
  theme_minimal(base_size = 12)

Interpretation

The boxplot compares the distribution of diamond weight across the five cut quality categories: Fair, Good, Very Good, Premium, and Ideal. The distributions show that diamond weight varies within every cut quality category, with the median and spread differing somewhat between groups. The box plots also contain several outliers, representing diamonds with unusually large weights compared with most diamonds in their respective cut quality category. There is considerable overlap between the groups, indicating that cut quality is not the only factor associated with diamond weight. Overall, the plot shows that diamonds of different cut quality levels can have a wide range of weights.

  1. Relationship - Diamond_Sample
set.seed(123)
diamonds_sample <- diamonds %>%
  slice_sample(n = 1000)

ggplot(diamonds_sample,
       aes(x = carat, y = price)) +
  geom_point(aes(color = clarity), alpha = 0.6) +
  geom_smooth(
    method = "lm",
    se = FALSE
  ) +
  labs(
    title = "Relationship Between Diamond Weight and Price",
    x = "Diamond Weight",
    y = "Price (USD)",
    color = "Clarity"
  ) +
  theme_minimal()
`geom_smooth()` using formula = 'y ~ x'

Interpretation

The scatterplot shows a clear positive relationship between diamond weight and price. In general, diamonds with greater weight tend to have higher prices. However, the points are widely dispersed, indicating that diamond weight alone does not fully explain differences in price. The different colors representing clarity also show variation in price among diamonds with similar weights, suggesting that clarity is another factor associated with diamond price. Overall, the visualization indicates that both diamond weight and clarity are related to differences in diamond prices.

  1. Time Series - Economics
ggplot(economics,
       aes(x = date, y = psavert)) +
  geom_line() +
  labs(
    title = "Personal Saving Rate Over Time",
    x = "Year",
    y = "Personal Saving Rate (%)"
  ) +
  theme_minimal()

Improved Visualization with a Highlighted Period

ggplot(economics,
       aes(x = date, y = psavert)) +
  geom_line() +
  geom_vline(
    xintercept = as.Date("2008-09-01"),
    linetype = "dashed"
  ) +
  annotate(
    "text",
    x = as.Date("2008-09-01"),
    y = max(economics$psavert),
    label = "2008 financial crisis period",
    hjust = 1.01,
    vjust = 1
  ) +
  labs(
    title = "Personal Saving Rate Over Time",
    subtitle = "Monthly observations from the economics dataset",
    x = "Year",
    y = "Personal Saving Rate (%)"
  ) +
  theme_minimal()

Interpretation

The time-series plot shows that the personal saving rate varies considerably over time, with periods of both relatively low and high saving rates. A noticeable increase occurs around the 2008 - 2009 financial crisis period, when the saving rate rises compared with the preceding years. The plot also shows that the saving rate does not follow a constant pattern, indicating changes in saving behavior over time. Overall, the visualization highlights substantial variation in the personal saving rate and provides a clear view of how it changed during the financial crisis period.

  1. To improve a visualization
ggplot(economics, aes(x = pop, y = unemploy)) +
  geom_point(alpha = 0.6) +
  labs(
    title = "Population and Unemployment",
    x = "Population",
    y = "Number Unemployed"
  ) +
  theme_minimal()

The original visualization shows the relationship between population and the number of unemployed people. However, all observations have the same appearance, so the personal saving rate cannot be distinguished.

Redesigned Visualization

economics2 <- economics %>%
  mutate(
    saving_group = cut(
      psavert,
      breaks = c(-Inf, 5, 10, Inf),
      labels = c("Low (<5%)", "Medium (5–10%)", "High (>10%)")
    )
  )

  ggplot(economics2,
         aes(x = pop,
             y = unemploy,
             color = saving_group)) +
  geom_point(
    size = 2.5,
    alpha = 0.7
  ) +
  labs(
    title = "Population and Unemployment by Saving Rate",
    subtitle = "Colour represents personal saving rate categories",
    x = "Population",
    y = "Number Unemployed",
    color = "Saving Rate"
  ) +
  theme_minimal(base_size = 12)

Interpretation

The improved visualization provides a clearer view of the relationship between population and unemployment while simultaneously distinguishing observations by their personal saving-rate category. The use of color makes it easier to identify whether each observation belongs to the low, medium, or high saving-rate group. This additional categorization allows the distribution and potential patterns within the data to be examined more effectively across different saving-rate levels.