Classwork 12

Distribution of a Categorical Variable

Author

Byeong-Hak Choe

Published

October 21, 2026

NoteNote

Complete the questions and submit your responses on the corresponding Brightspace page.

Complete the code in an R script and keep your brief written interpretations with it. This page contains its own setup and data definitions; no earlier classwork is required.

Setup and data

library(tidyverse)

The built-in mpg data contains 234 vehicle model configurations from model years 1999 and 2008. Each row represents a configuration, not an individual driver or purchase. The variable class identifies the vehicle category, such as compact or SUV. Dataset reference: ggplot2 · mpg.

1. Rows become counts

Count vehicle configurations in each category using horizontal bars.

ggplot(data = mpg,
       mapping = aes(y = ____,
                     fill = class)) +
  ____()

What does the length of each bar represent? Why would these bars be insufficient evidence about which category sells the most vehicles?

2. Counts already stored in a table

Run this supplied preparation code. count(class) creates one row per category and stores the number of configurations in a new column named n.

class_counts <- mpg |>
  count(class)
class n
2seater 5
compact 47
midsize 41
minivan 11
pickup 33
subcompact 35
suv 62

Plot those existing counts with geom_col().

ggplot(data = class_counts,
       mapping = aes(x = ____,
                     y = class,
                     fill = class)) +
  ____()

Explain why geom_col() suits class_counts, while geom_bar() suits the original mpg table.

3. A sorted comparison

Use this supplied version to place the category labels on the vertical axis and sort by count. fct_reorder(class, n) orders the category labels using n.

ggplot(data = class_counts,
       mapping = aes(x = n,
                     y = fct_reorder(class, n),
                     fill = class)) +
  geom_col()

Identify the largest and smallest categories in this dataset. Which version makes the comparison easier: the original category order or the sorted version?

Back to top