🚧 Under construction — VoTechWorks is being built. A free tech program — complimentary, as our commitment to get America working.
voTechWorksGrade 13 · a vocational technology learning center, by urbanicity
newSchoolWorks.com › VoTechWorks › Technology & Design › Data Science & Analytics › Data Visualization: Principles, Tools, and Storytelling › Lesson 5
TEC-DATA85-06 · Lesson 5 · 11 clock hours · lab

Visualization in R: ggplot2 and the Grammar of Graphics

Objective. Students will construct a layered ggplot2 visualization in R using geom, aesthetic mapping, faceting, and a custom theme, and export it as a 300 dpi PNG file.

⚠ Pending professional review

This lesson, its worked examples and its practice questions has not yet been verified by an industry-certified professional or by a certification or approval body. It is a study draft and may contain errors. Do not use it as instructions for work on a job site or on live equipment. Always follow your instructor, your supervising professional, and current official references and regulations.

VoTechWorks program approval and accreditation are still in progress. Credentials are issued only by the certifying bodies named in each program, after their own exams.

Visualization in R: ggplot2 and the Grammar of Graphics

What Is the Grammar of Graphics?

In 2005, statistician Leland Wilkinson published The Grammar of Graphics, a framework that describes every statistical chart as a combination of independent, composable layers. Hadley Wickham adapted this framework into the R package ggplot2, released as part of the tidyverse. Instead of memorizing dozens of separate chart functions, you learn one consistent grammar and combine its parts to build almost any visualization imaginable.

The framework has six core components:

| Component | What it does | Example ggplot2 function |

|-----------|-------------|-------------------------|

| Data | The data frame being visualized | `ggplot(data = mpg)` |

| Aesthetics | Mappings from data variables to visual properties | `aes(x = displ, y = hwy, color = class)` |

| Geometries | The geometric shapes that represent data | `geom_point()`, `geom_bar()`, `geom_line()` |

| Statistics | Statistical transformations applied before plotting | `stat_smooth()`, `stat_bin()` |

| Coordinates | The coordinate system | `coord_flip()`, `coord_polar()` |

| Themes | Non-data visual styling | `theme_minimal()`, `theme_bw()` |

Faceting—splitting one plot into small multiples by a categorical variable—is a seventh practical tool, handled by `facet_wrap()` or `facet_grid()`.

Building a ggplot2 Plot Layer by Layer

The key mental model is that you add layers with `+`. Start with the canvas, then pile on geometry, aesthetics, facets, labels, and a theme one at a time.

Step 1 – Canvas

```r

ggplot(data = mpg, aes(x = displ, y = hwy))

```

This creates a blank coordinate plane. No points appear yet because no geometry has been specified.

Step 2 – Add geometry

```r

ggplot(data = mpg, aes(x = displ, y = hwy)) +

geom_point()

```

Now dots appear: engine displacement (liters) on the x-axis, highway miles per gallon on the y-axis.

Step 3 – Add a color aesthetic

```r

ggplot(data = mpg, aes(x = displ, y = hwy, color = class)) +

geom_point()

```

Maping `color` to `class` inside `aes()` tells ggplot2 to assign a distinct color to each vehicle class automatically and generate a legend.

Step 4 – Add faceting

```r

ggplot(data = mpg, aes(x = displ, y = hwy, color = class)) +

geom_point() +

facet_wrap(~ drv)

```

`facet_wrap(~ drv)` splits the plot into one panel per drive-train type (front, rear, four-wheel). Each panel shares the same axes, making comparisons honest.

Step 5 – Apply a theme and add labels

```r

ggplot(data = mpg, aes(x = displ, y = hwy, color = class)) +

geom_point() +

facet_wrap(~ drv) +

theme_minimal() +

labs(

title = "Engine Size vs. Highway MPG by Drive Train",

x = "Engine Displacement (L)",

y = "Highway MPG",

color = "Vehicle Class"

)

```

`theme_minimal()` removes the default grey background. `labs()` replaces machine-readable column names with human-readable labels. These two steps are often what separate a draft chart from a professional deliverable.

Exporting at 300 dpi

Screen resolution (72–96 dpi) is fine for on-screen viewing but insufficient for print or formal reports. Publication and most employer standards require 300 dpi minimum. Use `ggsave()` immediately after running your plot:

```r

ggsave(

filename = "my_chart.png",

plot = last_plot(),

width = 8,

height = 5,

units = "in",

dpi = 300

)

```

`last_plot()` captures whatever ggplot2 drew most recently. You can also assign your plot to an object (e.g., `p <- ggplot(...)`) and pass `plot = p` directly.

Aesthetic Mappings vs. Fixed Properties

A common source of confusion: aesthetics that belong inside `aes()` are data-driven; properties set outside `aes()` are fixed for every point.

Mixing these up produces errors or silent misgrouping, which is a frequent debugging task in the field.

Reproducibility and Script Hygiene

Data science work must be reproducible. Write your code in an `.R` script (not the console) and include these practices:

1. Load all packages at the top with `library(tidyverse)`.

2. Set a relative file path when reading CSV data so the script runs on any machine that has the project folder.

3. Place `ggsave()` at the bottom of the script so export is automatic whenever the script is sourced.

4. Add brief comments (`#`) to explain non-obvious choices.

Workplace Data Safety Notes

Data visualization work involves real datasets that may contain personally identifiable information (PII) or confidential business data. Before loading any provided CSV:

These habits align with data-handling expectations tested on CompTIA Data+ and practiced across all four credentials in this program.

Reference

All syntax and concepts in this lesson are covered in R for Data Science by Hadley Wickham, Chapters 3 and 28, freely available at r4ds.had.co.nz.

Key terms10

Grammar of GraphicsA framework, formalized by Leland Wilkinson and implemented in ggplot2, that breaks every statistical chart into composable layers: data, aesthetics, geometries, statistics, coordinates, and themes.
aesthetic mapping (aes)A declaration inside aes() that links a column in the data frame to a visual property of the geometry, such as x position, y position, color, size, or shape.
geometry (geom)The type of mark used to represent data in a plot; examples include geom_point() for scatter plots, geom_line() for line charts, and geom_bar() for bar charts.
facetingThe technique of splitting one plot into an array of small-multiple panels, each showing a subset of the data defined by a categorical variable, using facet_wrap() or facet_grid() in ggplot2.
themeThe non-data visual styling of a ggplot2 plot, controlling background color, gridlines, font sizes, and other decorative elements; applied with functions like theme_minimal() or theme_bw().
ggsave()The ggplot2 function that exports a plot to a file; accepts arguments for file format, width, height, units, and dpi to control output quality.
dpi (dots per inch)A measure of image resolution; 300 dpi is the standard minimum for print-quality output in professional and publication contexts.
facet_wrap()A ggplot2 function that creates small-multiple panels by wrapping facets across rows and columns based on one categorical variable specified with tilde notation, e.g., facet_wrap(~ variable).
labs()A ggplot2 function used to set human-readable labels for the title, axis titles, legend titles, and captions of a plot.
tidyverseA curated collection of R packages, including ggplot2, dplyr, readr, and others, designed around a consistent philosophy for data import, transformation, and visualization.
In class: Lecture on Hadley Wickham's Grammar of Graphics framework: data, aesthetics, geometries, statistics, coordinates, and themes—students complete a concept map that maps each layer to a concrete ggplot2 function. · Guided coding exercise in RStudio: students build a faceted scatter plot of the built-in 'mpg' dataset step-by-step, adding layers one at a time (geom_point → color aesthetic → facet_wrap → theme_minimal → labs), running the plot after each addition to see incremental changes. · Independent challenge: students reproduce a target chart (provided as a PNG image) using a new dataset (provided CSV), matching axis labels, facets, and color scheme as closely as possible, then export the result using ggsave() at 300 dpi.
Materials: RStudio, R 4.x, ggplot2 package (part of tidyverse), provided CSV dataset, target chart PNG handout, 'R for Data Science' by Hadley Wickham (Ch. 3 and 28, freely available at r4ds.had.co.nz).
Check: Submitted .R script and exported PNG. Instructor checks: plot renders from script without error, faceting is present, custom theme applied, file is 300 dpi. Pass = all four criteria met.

Practice check8

Answer each question, then check it. Nothing is recorded; this is your own practice.

Data visualization concepts
1. In ggplot2's Grammar of Graphics, which layer is responsible for the geometric shapes drawn on the plot—for example, points in a scatter plot or bars in a bar chart?
Data visualization concepts
2. A student writes: `geom_point(color = "blue")`. What is the effect compared to writing `aes(color = class)`?
Data visualization tools
3. Which ggplot2 function splits a single plot into multiple panels, one for each level of a categorical variable?
Data visualization tools
4. A data analyst needs to export a ggplot2 chart as a PNG file at 300 dpi for a printed report. Which code correctly accomplishes this?
Data management and reproducibility
5. Why is it best practice to load packages at the top of an R script rather than mid-script or in the console?
Data visualization concepts
6. A student wants to add a smoothed trend line to an existing scatter plot built with geom_point(). According to the Grammar of Graphics, which ggplot2 addition is most appropriate?
Data governance and ethics
7. Which of the following best describes a data security responsibility when working with a provided CSV dataset that may contain personally identifiable information (PII)?
Data visualization storytelling
8. In the context of the Google Data Analytics Certificate and CompTIA Data+ exam objectives, which best describes why faceted charts (small multiples) are preferred over plotting all groups on a single overlapping chart?
Record this lesson on my transcript. Sign in with your key and enrollment email to record lessons (enroll free if you have no key). This page stays open to read and practise.