mpg_summary <- mpg %>%
  group_by(class) %>%
  summarise(
    mean_cty = mean(cty),
    mean_hwy = mean(hwy)
  ) %>%
  
  pivot_longer(
    cols = c(mean_cty, mean_hwy), 
    names_to = "mileage_type", 
    values_to = "mpg_value"
  )


knitr::kable(head(mpg_summary), caption = "Average MPG by Vehicle Class")
Average MPG by Vehicle Class
class mileage_type mpg_value
2seater mean_cty 15.40000
2seater mean_hwy 24.80000
compact mean_cty 20.12766
compact mean_hwy 28.29787
midsize mean_cty 18.75610
midsize mean_hwy 27.29268
hex_plot <- ggplot(mpg, aes(x = displ, y = hwy)) +
  geom_hex(bins = 15, color = "black", linewidth = 0.1) +
  scale_fill_viridis_c(name = "Count") +
  theme_cowplot() +
  labs(
    title = "Engine Size vs. Highway MPG",
    x = "Displacement (Liters)",
    y = "Highway MPG"
  )


bar_plot <- ggplot(mpg_summary, aes(x = class, y = mpg_value, fill = mileage_type)) +
  geom_col(position = "dodge", alpha = 0.8, color = "black") +
  scale_fill_manual(
    values = c("mean_cty" = "coral", "mean_hwy" = "steelblue"),
    labels = c("City MPG", "Highway MPG"),
    name = "Mileage Type"
  ) +
  theme_cowplot() +
  labs(
    title = "Average MPG by Vehicle Class",
    x = "Vehicle Class",
    y = "Miles Per Gallon"
  ) +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))


plot_grid(hex_plot, bar_plot, labels = c("A", "B"), ncol = 2, rel_widths = c(1, 1.2))