Introduction

WarningCaution

This section is still being developed. The contents are subject to change.

ggplot2 syntax

“making infinite use of finite means” (Wilhelm von Humboldt)

Grammar is often defined as the system of rules for any given language and includes word meanings, internal structures, and word arrangement. Syntax is the form, structure and order used to construct statements. ggplot2’s syntax is built on the grammar & syntax of R. In R, objects are like nouns, and functions are like verbs (i.e., functions “do things” to objects).

ggplot2 syntax is built on layers, which we can use as templates to build increasingly customized and complex graphs.

The Data Layer

The data layer consists of a rectangular object (like a spreadsheet) with columns and rows. Every dataset in this book is simulated, so we’ll create one here: 150 home PCs sold in 1998, with each PC’s brand, operating system (os), processor speed (cpu_mhz), and price (price_usd). Faster processors cost more, and Windows 98 adds a little to the price.

show/hide
set.seed(1998)
pc_sales <- tibble(
  brand = sample(c("Compaq", "Dell", "Gateway"), 150, replace = TRUE),
  os = sample(c("Windows 95", "Windows 98"), 150, replace = TRUE, 
    prob = c(0.4, 0.6)),
  cpu_mhz = sample(c(133, 166, 200, 233, 266, 300, 350, 400), 150, 
    replace = TRUE),
  price_usd = round(700 + 4 * cpu_mhz + 
    if_else(os == "Windows 98", 150, 0) + rnorm(150, 0, 200)))
ggplot(data = pc_sales)

The Mapping Layer

The mapping layer assigns columns (variables) from the data to a visual property (i.e. graph ’aes’ thetic).

show/hide
ggplot(data = pc_sales,
  mapping = 
    aes(
      x = cpu_mhz, y = price_usd
      )
  )

Plan 1: data, aesthetic mappings, and a geom

ggplot(data = <DATA>) +
  geom_*(mapping = aes(<AESTHETIC MAPPINGS>))

The Stats/Geoms Layer

geom_*() functions include statistical transformations, shapes, and position adjustments for how to ‘draw’ the data on the graph

show/hide
ggplot(data = pc_sales,
  mapping = aes(
    x = cpu_mhz, y = price_usd
    )
  ) +
  geom_point(
    aes(
      shape = brand, color = os
      )
    )

We can have multiple layers (data, mappings, geoms) in a single graph.

show/hide
ggplot(data = pc_sales,
 # layer 1
  mapping = aes(
    x = cpu_mhz, y = price_usd
    )
  ) +
  geom_point(
    aes(
      shape = brand, color = os
      )
    ) +
# layer 2
  geom_smooth(
    mapping = aes(
      x = cpu_mhz, y = price_usd), 
        se = FALSE
    )

Plan 2: Plan 1 + a second geom (and its aesthetic mappings)

ggplot(data = <DATA>) +
    geom_*(mapping = aes(<AESTHETIC MAPPINGS>)) +
    geom_*(mapping = aes(<AESTHETIC MAPPINGS>))

Position, Labels & Themes

With a finite number of objects & functions, we can combine ggplot2’s grammar and syntax to create an infinite number of graphs.

show/hide
ggplot(data = pc_sales,
 # layer 1
  mapping = aes(
    x = cpu_mhz, y = price_usd
    )
  ) +
  geom_point(
    aes(
      color = os
      )
    ) +
# layer 2
  geom_smooth(
    mapping = aes(
      x = cpu_mhz, y = price_usd), 
        se = FALSE
    ) +
# layer 3
  facet_wrap(
    . ~ brand, ncol = 2
    ) + 
  # labels
  labs(
    x = 'Processor speed (MHz)', y = 'Price (USD)', 
    title = 'Home PCs in 1998',  subtitle = 'Faster processors cost more',
    caption = 'Simulated data', color = 'Operating system'
    ) + 
  # themes
  theme(legend.position = "bottom", legend.box = "vertical")

Plan 3: Plan 2 + facets, theme, and labels

ggplot(data = <DATA>) +
    geom_*(mapping = aes(<AESTHETIC MAPPINGS>)) +
    geom_*(mapping = aes(<AESTHETIC MAPPINGS>)) +
    facet_* +
    theme() +
    labs()

Graph Categories

Graphs have been categorized into the following types (you can see them in the floating table of contents to your left).

  • Univariate: if you have a single column you’re trying to visualize

  • Amounts: counts or simple summary statistics of one or two columns in a dataset

  • Proportions: ratio displays of part-to-whole

  • Distributions: displaying the shape of a variable’s values (normality, skewness, kurtosis, etc.)

  • Dates & Times: changes in quantitative or categorical variables over a dimension of time (date-time, date, year, month, quarter, etc.).

  • Relationships: how does the change of values in variable x affect the values in variable y (and possibly z)?

Some graphs can justifiably belong to more than one category. Wherever this is the case, I’ve tried to include links to other applications in the notes.

Assumptions

I’ve tried to write code so it can be read and understood without executing it.1 However, the examples assume readers can investigate R objects and answer questions related to their structure.2

Style & structure

Each graph has the following sections:

  1. Theme

    • The color palette and font for the chapter’s graphs, and the piece of 90s pop culture they’re modeled on.
  2. Requirements

    • What this graph requires, and a preview of the graph.
  3. Description

    • A brief summary of the graph’s background, purpose, and aesthetics.
  4. Set up

    • Packages
      • Code for installing development version of packages (if necessary) for graphs.
    • Data
      • The code that simulates the data for the graph (with set.seed(), so you get the same values every time).
  5. Distribution

    • How the distribution we simulated from shapes the graph, in four steps:
      • COUNT IT: look at a handful of values and a few summary numbers.
      • DRAW IT: draw the data as a bar model or annotated graph.
      • NAME IT: write down the distribution and connect each parameter to the graph.
      • CHANGE IT: change the data (a smaller sample, a new group, a different distribution) and redraw the same graph to show something unexpected.
  6. Grammar

    • Code
      • The steps for building the graph, followed by the code.
      • Graph labels have the labs_ prefix
      • Graph layers have a ggp2_ prefix
    • Graph
      • The finished graph.
  7. More info (in some chapters)

    • Additional methods, arguments, or applications
      • Color palettes
      • Complementary packages

The diagram below shows how the sections fit together. The data is simulated in Set up, explained and then changed in Distribution, and graphed in Grammar.

%%{init: {'theme': 'base', 'themeVariables': { 'fontFamily': 'monospace', 'fontSize': '14px', 'darkMode': false}}}%%

flowchart TD
    thm(["<strong>Theme</strong><br>colors + letters"]) --> req(["<strong>Requirements</strong><br>what the graph needs"]) --> desc["<strong>Description</strong><br>what the graph shows"]
    desc --> setup[/"<strong>Set up</strong><br>packages + simulated data"/]
    setup --> dist
    subgraph dist["<strong>Distribution</strong>"]
        count["i. COUNT IT<br>values + summaries"] --> draw["ii. DRAW IT<br>bar model or<br>annotated graph"]
        draw --> name["iii. NAME IT<br>distribution +<br>parameters"]
        name --> change["iv. CHANGE IT<br>new data +<br>same graph"]
    end
    dist --> grammar[["<strong>Grammar</strong><br><code>labs_*</code> + <code>ggp2_*</code>"]]
    grammar --> more(["<strong>More info</strong><br>other geoms + options<br>(some chapters)"])

    style thm fill:#4CBB9D,color:#FFFFFF,rx:5,ry:5
    style req fill:#4CBB9D,color:#FFFFFF,rx:5,ry:5
    style desc fill:#FFFFFF,color:#000000,stroke:#333
    style setup fill:#C0C0C0,color:#000000,stroke:#333
    style dist fill:#FFFFFF,color:#000000,stroke:#333,stroke-width:1px,rx:10,ry:10
    style count fill:#000080,color:#FFFFFF,rx:5,ry:5
    style draw fill:#000080,color:#FFFFFF,rx:5,ry:5
    style name fill:#000080,color:#FFFFFF,rx:5,ry:5
    style change fill:#000080,color:#FFFFFF,rx:5,ry:5
    style grammar fill:#FFFFFF,color:#000000,stroke:#333
    style more fill:#4CBB9D,color:#FFFFFF,rx:5,ry:5

The sections in each graph chapter

I’ve attempted to balance brevity and clarity, but with the assumption that it’s best to err on the latter. I’ve also followed the general principle that if a graph can be easily built using one of ggplot2’s geom_* functions, that method is shown first.

The first section (Univariate) starts with bar graphs, which count how often each category appears in a single column.


  1. This field manual follows The Rule of Least Power, in the sense that “a language with a straightforward syntax may be easier to analyze than an otherwise equivalent one with more complex structure.”↩︎

  2. If not, I highly recommend the skimr and inspectdf packages for getting to know your data better.↩︎