Exercises

ggplot(mpg, aes(cty, hwy)) + 
  geom_jitter()

ggplot(mpg, aes(class, hwy)) + 
  geom_boxplot()

ggplot(mpg, aes(reorder(class, hwy), hwy)) + 
  geom_boxplot()

  1. By default, reorder() sorts the factor levels by the median

  2. The weight aesthetic in geom_bar() allows you to specify the weight or frequency for each observation

ggplot(mpg, aes(x = class, weight = cty)) + 
  geom_bar()

ggplot(mpg, aes(x = model, fill = manufacturer)) + 
  geom_bar(position = "dodge")

library(dplyr)

# summarized data frame
summary_data <- mpg %>%
  count(trans, class)

# heatmap-like plot using geom_tile
ggplot(summary_data, aes(x = trans, y = class)) + 
  geom_tile(aes(fill = n), width = 1, height = 1)

ggplot(summary_data, aes(x = trans, y = class)) + 
  geom_tile(aes(fill = n), width = 1, height = 1) +
  scale_fill_viridis_c()