Lab 4: Visualization in Practice with ggplot2

Student Summary and Lab Activity

Author

Abeer Hasan

1 Overview

This week connects two complementary skills. First, you will use the grammar of graphics implemented in ggplot2 to construct plots layer by layer. Second, you will apply data-visualization principles to decide whether a graph communicates quantities, distributions, and relationships accurately.

The goal is not simply to produce a plot that runs. A successful visualization should match the analytical question, represent the data faithfully, make comparisons easy, and remain interpretable to its intended audience.

1.1 Primary readings

1.2 Learning outcomes

By the end of this lab, you should be able to:

  1. construct statistical graphics by combining data, aesthetic mappings, geometries, scales, annotations, and themes;
  2. distinguish an aesthetic mapping from a fixed graphical setting;
  3. select displays for quantities, distributions, group comparisons, and relationships;
  4. use transformations when they improve the visibility and interpretation of skewed data;
  5. identify graphical choices that exaggerate, conceal, or distort differences;
  6. improve comparisons through meaningful ordering, common axes, adjacency, and direct display of the data; and
  7. produce readable graphics using clear labels and color-blind-friendly encodings.

2 Reading summary

2.1 Chapter 8: Building plots with ggplot2

ggplot2 uses a grammar of graphics: a plot is assembled from components rather than selected as a fixed chart type. The basic structure is:

data |>
  ggplot(aes(x = x_variable, y = y_variable)) +
  geom_name()

The principal components are:

Component Purpose Examples
Data Supplies the observations and variables murders, heights
Aesthetic mapping Connects variables to visible properties aes(x = population, y = total, color = region)
Geometry Determines how observations are drawn geom_point(), geom_col(), geom_histogram()
Scale Controls how mapped values appear on axes or in legends scale_x_log10(), scale_color_manual()
Annotation Adds explanatory information not necessarily mapped from variables labs(), annotate(), geom_abline()
Theme Controls non-data elements and overall appearance theme_minimal()

2.1.1 Mapped versus fixed properties

Place a graphical property inside aes() when its values should vary according to a variable. Place it outside aes() when every observation should receive the same setting.

# Color is mapped to a variable; ggplot2 creates a legend.
ggplot(murders, aes(population, total, color = region)) +
  geom_point()

# Every point is assigned the same navy color; no variable is mapped to color.
ggplot(murders, aes(population, total)) +
  geom_point(color = "#003B5C")

2.1.2 Common geometries

  • Use geom_point() for relationships between two quantitative variables.
  • Use geom_col() when bar heights are already stored in the data; use geom_bar() when counts should be computed from observations.
  • Use geom_histogram() or geom_density() to examine a quantitative distribution.
  • Use geom_boxplot() for compact comparisons of distributions, preferably supplemented with raw observations when feasible.
  • Use transparency through alpha and jitter through geom_jitter() to reduce overplotting.

2.1.3 Scales and transformations

A log scale can make multiplicative relationships and right-skewed data easier to inspect. A transformation should have an analytical reason and must be clearly communicated in the axis label. Do not use a transformation simply to make a figure look more balanced.

2.2 Chapter 9: Designing truthful and interpretable graphics

Chapter 9 moves from plot construction to graphical judgment. Its central principles include the following.

  1. Use visual cues people can compare accurately. Position along a common axis and aligned length are generally easier to judge than angle, area, brightness, or color intensity.
  2. Use zero appropriately. Bars encode quantity through length, so their baseline should normally be zero. Position-based displays, such as scatterplots or dot plots, need not always include zero when a restricted range clarifies meaningful variation.
  3. Do not distort quantities. Area-based symbols must scale by area rather than radius, but position or length is usually a clearer encoding.
  4. Order categories meaningfully. Alphabetical order is rarely the most informative choice. Order categories by the displayed value or another quantity connected to the question.
  5. Show the data. A mean with an error bar can conceal distributional shape, overlap, outliers, sample size, and within-group variability.
  6. Make comparisons easy. Use common axes, align plots in the direction of the comparison, and place the groups being compared next to each other.
  7. Use transformations deliberately. Log scales can reveal structure in right-skewed data and display multiplicative changes symmetrically.
  8. Use accessible colors. Do not depend on red-green differences alone. Combine color with position, shape, labels, or facets when needed.
  9. Avoid pseudo-three-dimensional displays. They introduce perspective and occlusion without adding reliable information.
  10. Match precision and complexity to the audience. Remove unnecessary digits and ensure that titles, axes, legends, and transformations are understandable to the intended reader.

3 Lab activity

3.1 Expected time and submission

  • Estimated time: 90–120 minutes
  • Submit: the completed .qmd file and its rendered HTML file
  • Evidence required: executable R code, all requested figures, and concise written interpretations
  • Reproducibility: restart R and render the document before submitting it

3.2 AI-use classification: AI-Permitted

Complete an initial attempt before consulting generative AI. You may use AI to explain an error message, locate relevant documentation, or critique a visualization you have already created. You may not ask AI to complete the entire lab or make the analytical decisions for you.

If you use AI, add a brief disclosure at the end that states what you asked, what suggestion you used or rejected, and how you verified the result. You remain responsible for the code, figures, and interpretations.

3.3 Setup

The lab uses ggplot2, dplyr, and the dslabs datasets. Install a missing package from the Console before rendering; do not place installation commands in the submitted document.

library(ggplot2)
library(dplyr)
library(dslabs)

colorblind_palette <- c(
  "#0072B2", "#D55E00", "#009E73", "#CC79A7",
  "#E69F00", "#56B4E9", "#F0E442", "#000000"
)

theme_set(theme_minimal(base_size = 12))

3.4 Part A: Constructing plots with the grammar of graphics

3.4.1 Exercise 1: Data, mappings, and geometry

Adapted from Chapter 8, Exercises 1–7.

  1. Inspect the structure and variable names of murders.
  2. Create a ggplot object named p associated with murders but with no geometry. Print it and explain why the result is a blank plotting area.
  3. Add a scatterplot layer with population on the horizontal axis and total murders on the vertical axis.
  4. In two or three sentences, identify the data, mapping, and geometry used in your completed plot.
# Your code

Interpretation:

Write your response here.

3.4.2 Exercise 2: Mapped versus fixed color

Adapted from Chapter 8, Exercises 8–13.

Create two versions of the scatterplot from Exercise 1:

  1. Assign the same navy color to every point.
  2. Map point color to region using aes() and apply colorblind_palette with scale_color_manual().
  3. Label the axes and legend clearly.
  4. Explain why one version produces a legend and the other does not.
# Your code

Explanation:

Write your response here.

3.4.3 Exercise 3: Labels, scales, and annotations

Adapted from Chapter 8, Exercises 9 and 14–16.

  1. Create a scatterplot of total murders against population.
  2. Use state abbreviations as text labels.
  3. Place both axes on log10 scales.
  4. Add an informative title, axis labels that identify the log scales, and a caption naming dslabs as the data source.
  5. Explain what becomes easier to see after the transformation and what a reader could misunderstand if the transformation were not labeled.
# Your code

Interpretation:

Write your response here.

3.4.4 Exercise 4: Histograms and analytical choices

Adapted from Chapter 8, Exercises 17–20.

Using the heights data:

  1. Create two histograms of height, one with binwidth = 1 and another with binwidth = 3.
  2. Give both plots the same horizontal limits and informative labels.
  3. Describe one feature that appears more or less prominent when the bin width changes.
  4. State why bin width is an analytical choice rather than a cosmetic setting.
# Your code

Comparison:

Write your response here.

3.4.5 Exercise 5: Comparing distributions

Adapted from Chapter 8, Exercises 21–24.

  1. Create density plots of height for the groups represented by sex.
  2. Use a color-blind-friendly palette, alpha transparency, clear labels, and a descriptive title.
  3. Then create a boxplot of height by sex with jittered observations overlaid.
  4. Compare what the density plot and the boxplot-plus-points reveal. Do not make causal claims.
# Your code

Comparison:

Write your response here.

3.5 Part B: Applying visualization principles

3.5.1 Exercise 6: Meaningful category order

Adapted from Chapter 9, Exercises 3–5.

The following code constructs state-level measles rates for 1967.

measles_1967 <- us_contagious_diseases |>
  filter(
    year == 1967,
    disease == "Measles",
    !is.na(population),
    !is.na(count),
    weeks_reporting > 0
  ) |>
  mutate(
    rate = count / population * 10000 * 52 / weeks_reporting
  )
  1. Create a horizontal bar chart with states in the default order.
  2. Create a revised chart that orders states by rate.
  3. Use a zero baseline, readable labels, and a title that includes the year and measurement unit.
  4. Explain which version better supports identification of the highest- and lowest-rate states.
# Your code

Evaluation:

Write your response here.

3.5.2 Exercise 7: Show the data, not only an average

Adapted from Chapter 9, Exercises 6–7.

  1. Calculate state murder rates per 100,000 residents.
  2. Reproduce a bar chart containing only the mean state rate for each region.
  3. Replace it with a boxplot that shows the regional distributions, orders regions by median rate, and overlays jittered state observations.
  4. Explain why choosing a region based only on the regional mean would be poorly supported. Refer specifically to within-region variability and overlap.
# Your code

Evaluation:

Write your response here.

3.5.3 Exercise 8: Visualization audit and redesign

Synthesizes Chapter 9 principles.

Return to one figure you created in Exercises 1–7. Audit it using the questions below, then revise the figure.

  1. Does the geometry match the analytical question?
  2. Are quantities encoded through position or length when feasible?
  3. Is zero included when length is the visual cue?
  4. Are categories ordered to support the comparison?
  5. Are relevant observations or distributions visible?
  6. Are scales, units, transformations, and data sources labeled?
  7. Can the figure be interpreted without distinguishing red from green?
  8. Are the title and precision appropriate for the intended audience?
# Revised figure

Audit summary:

Identify at least three changes and explain how each change improves statistical interpretation or communication.

3.6 Graduate extension

Complete this section if assigned for the graduate version of the course.

3.6.1 Exercise 9: Sensitivity of distribution displays

Using one quantitative variable from heights or murders, construct a small sensitivity analysis:

  1. Compare at least three defensible histogram bin widths or density bandwidth adjustments.
  2. Keep all other mappings and scales constant.
  3. Identify which features persist across the displays and which depend on the smoothing or binning choice.
  4. Defend one display for exploratory analysis and one for communication to a general audience. They may be the same, but the justification must address the audience and the risk of overinterpretation.
# Your code

Sensitivity analysis:

Write your response here.

3.6.2 Exercise 10: Redesign under competing goals

Create two visualizations from the same data and analytical question:

  • an exploratory version intended for a data analyst; and
  • a communication version intended for a general audience.

The two figures may differ in annotation, labeling, transformation, displayed detail, or use of direct labels. Explain what information you preserved, simplified, or emphasized in each version. Neither version may distort the underlying quantities.

# Your code

Design justification:

Write your response here.

4 Final verification checklist

Before submitting, confirm that:

5 AI-use disclosure

If you did not use generative AI, write: No generative AI was used.

If you used generative AI, complete the following:

  • Tool and purpose:
  • What I accepted, modified, or rejected:
  • How I verified the result:

6 Sources

This student summary and lab were developed from:

The lab questions select, combine, and adapt concepts and exercises from both chapters for instructional use.