Lab 4: Visualization in Practice with ggplot2
Student Summary and Lab Activity
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.2 Learning outcomes
By the end of this lab, you should be able to:
- construct statistical graphics by combining data, aesthetic mappings, geometries, scales, annotations, and themes;
- distinguish an aesthetic mapping from a fixed graphical setting;
- select displays for quantities, distributions, group comparisons, and relationships;
- use transformations when they improve the visibility and interpretation of skewed data;
- identify graphical choices that exaggerate, conceal, or distort differences;
- improve comparisons through meaningful ordering, common axes, adjacency, and direct display of the data; and
- 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; usegeom_bar()when counts should be computed from observations. - Use
geom_histogram()orgeom_density()to examine a quantitative distribution. - Use
geom_boxplot()for compact comparisons of distributions, preferably supplemented with raw observations when feasible. - Use transparency through
alphaand jitter throughgeom_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.
- 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.
- 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.
- Do not distort quantities. Area-based symbols must scale by area rather than radius, but position or length is usually a clearer encoding.
- Order categories meaningfully. Alphabetical order is rarely the most informative choice. Order categories by the displayed value or another quantity connected to the question.
- Show the data. A mean with an error bar can conceal distributional shape, overlap, outliers, sample size, and within-group variability.
- Make comparisons easy. Use common axes, align plots in the direction of the comparison, and place the groups being compared next to each other.
- Use transformations deliberately. Log scales can reveal structure in right-skewed data and display multiplicative changes symmetrically.
- Use accessible colors. Do not depend on red-green differences alone. Combine color with position, shape, labels, or facets when needed.
- Avoid pseudo-three-dimensional displays. They introduce perspective and occlusion without adding reliable information.
- 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
.qmdfile 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.
- Inspect the structure and variable names of
murders. - Create a
ggplotobject namedpassociated withmurdersbut with no geometry. Print it and explain why the result is a blank plotting area. - Add a scatterplot layer with population on the horizontal axis and total murders on the vertical axis.
- In two or three sentences, identify the data, mapping, and geometry used in your completed plot.
# Your codeInterpretation:
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:
- Assign the same navy color to every point.
- Map point color to
regionusingaes()and applycolorblind_palettewithscale_color_manual(). - Label the axes and legend clearly.
- Explain why one version produces a legend and the other does not.
# Your codeExplanation:
Write your response here.
3.4.3 Exercise 3: Labels, scales, and annotations
Adapted from Chapter 8, Exercises 9 and 14–16.
- Create a scatterplot of total murders against population.
- Use state abbreviations as text labels.
- Place both axes on log10 scales.
- Add an informative title, axis labels that identify the log scales, and a caption naming
dslabsas the data source. - Explain what becomes easier to see after the transformation and what a reader could misunderstand if the transformation were not labeled.
# Your codeInterpretation:
Write your response here.
3.4.4 Exercise 4: Histograms and analytical choices
Adapted from Chapter 8, Exercises 17–20.
Using the heights data:
- Create two histograms of
height, one withbinwidth = 1and another withbinwidth = 3. - Give both plots the same horizontal limits and informative labels.
- Describe one feature that appears more or less prominent when the bin width changes.
- State why bin width is an analytical choice rather than a cosmetic setting.
# Your codeComparison:
Write your response here.
3.4.5 Exercise 5: Comparing distributions
Adapted from Chapter 8, Exercises 21–24.
- Create density plots of height for the groups represented by
sex. - Use a color-blind-friendly palette,
alphatransparency, clear labels, and a descriptive title. - Then create a boxplot of height by
sexwith jittered observations overlaid. - Compare what the density plot and the boxplot-plus-points reveal. Do not make causal claims.
# Your codeComparison:
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
)- Create a horizontal bar chart with states in the default order.
- Create a revised chart that orders states by
rate. - Use a zero baseline, readable labels, and a title that includes the year and measurement unit.
- Explain which version better supports identification of the highest- and lowest-rate states.
# Your codeEvaluation:
Write your response here.
3.5.2 Exercise 7: Show the data, not only an average
Adapted from Chapter 9, Exercises 6–7.
- Calculate state murder rates per 100,000 residents.
- Reproduce a bar chart containing only the mean state rate for each region.
- Replace it with a boxplot that shows the regional distributions, orders regions by median rate, and overlays jittered state observations.
- Explain why choosing a region based only on the regional mean would be poorly supported. Refer specifically to within-region variability and overlap.
# Your codeEvaluation:
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.
- Does the geometry match the analytical question?
- Are quantities encoded through position or length when feasible?
- Is zero included when length is the visual cue?
- Are categories ordered to support the comparison?
- Are relevant observations or distributions visible?
- Are scales, units, transformations, and data sources labeled?
- Can the figure be interpreted without distinguishing red from green?
- Are the title and precision appropriate for the intended audience?
# Revised figureAudit 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:
- Compare at least three defensible histogram bin widths or density bandwidth adjustments.
- Keep all other mappings and scales constant.
- Identify which features persist across the displays and which depend on the smoothing or binning choice.
- 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 codeSensitivity 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 codeDesign 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:
- Irizarry, R. A. Introduction to Data Science, Chapter 8: ggplot2.
- Irizarry, R. A. Introduction to Data Science, Chapter 9: Data visualization principles.
The lab questions select, combine, and adapt concepts and exercises from both chapters for instructional use.