From Principles To Practice

  • Week 2: Principles of data visualisation
  • Week 3: Grammar of Graphics; aesthetics and attributes
  • Week 4: Major visualisation tools
  • Week 5: Customising visualisations (scales, themes, and labels)

What You Should Take Away

By the end of the session, you should be able to:

  • read a ggplot2 plot as a set of layers
  • explain the difference between aesthetics and attributes
  • choose simple aesthetic mappings for continuous and categorical variables
  • avoid overloaded mappings that make plots harder to read

Download the Week 3 files from NOW and move them into your RStudio Project folder.

There are two exercise files for today:

  • 01_building_ggplot_layers.Rmd
  • 02_aesthetics_vs_attributes.Rmd

Building Plots With Grammar

What Parts Make Up This Plot?

Before we name the grammar, look at the plot and identify what it is made from.

What do you notice about the data, visual marks, colours, lines, labels, and layout?

Core Components

Component Example Description
Data d_spellname The dataset being plotted
Aesthetics (aes) x = dur, y = rt How data variables map to visual properties
Geometries (geom) geom_point() The type of plot element (points, bars, lines)
Statistics (stat) stat_smooth() Transformations of data (e.g., regression lines)
Scales scale_x_log10() How data values are converted to aesthetics
Facets facet_wrap(~group) Splitting data into small multiples
Coordinate system coord_polar() The space where data are drawn (Cartesian, polar)
Theme theme_minimal() Non-data display elements (fonts, text, grids, etc.)

Why ggplot2 Uses A Grammar

Wilkinson (2005)

  • ggplot2 is an R package for creating data visualisations.
  • The “gg” stands for Grammar of Graphics (Wilkinson, 2005).
  • A grammar means plots are built from reusable parts, rather than memorised as separate plot types.
  • This helps you start simple and add complexity only when it helps the reader.
  • See also Wickham (2016), Wickham (2010).

What The Grammar Describes

Wilkinson (2005)

A statistical graphic connects three main things:

  • data: the variables we want to show
  • aesthetics: how variables become visual properties such as position, colour, shape, or size
  • geometries: the visible marks, such as points, lines, or bars

Other layers can then summarise, split, transform, label, or style the plot.

Grammar As Building Blocks

Wilkinson (2005)

Think about language: grammar tells us how words can be combined into sentences.

For plots, the grammar tells us how data, mappings, and visual marks can be combined.

The practical skill for today is to read a plot as layers: What data are used? What is mapped? What is drawn? What else has been added?

The Three Required Parts

  • data: the data you want to visualise indicated as ggplot(data = ...)
  • aesthetics: mapping of data to graphic properties (axes, size, colour) indicated as mapping = aes()
  • geometries: visual elements encoding the data indicated as geom_...()

Required Parts: Data And Aesthetics

ggplot(d_spellname, aes(x = dur, y = rt))

Add A Geometry: Points

ggplot(d_spellname, aes(x = dur, y = rt)) +
  geom_point()

Change The Geometry: Quantiles

ggplot(d_spellname, aes(x = dur, y = rt)) +
  geom_quantile()

Change The Geometry: Rug Marks

ggplot(d_spellname, aes(x = dur, y = rt)) +
  geom_rug()

Combine Multiple Geometries

ggplot(d_spellname, aes(x = dur, y = rt)) +
  geom_point() +
  geom_quantile() +
  geom_rug()

Layers You Can Add Later

  • facets: dividing data into subplots
  • statistics: statistical summaries
  • coordinates: how the plotting space is arranged
  • theme: visual properties not related to the data (font, background)

Start With Data, Aesthetics, And Geometry

  • data
  • aesthetics
  • geometries

ggplot(d_spellname, aes(x = dur, y = rt)) +
  geom_point()

Add Facets To Split The Plot

  • data
  • aesthetics
  • geometries
  • facets

ggplot(d_spellname, aes(x = dur, y = rt)) +
  geom_point() +
  facet_grid( ~ modality)

Add A Statistical Summary

  • data
  • aesthetics
  • geometries
  • facets
  • statistics

ggplot(d_spellname, aes(x = dur, y = rt)) +
  geom_point() +
  stat_smooth(method = "lm", se = FALSE) 

Change The Coordinate System

  • data
  • aesthetics
  • geometries
  • facets
  • statistics
  • coordinates

ggplot(d_spellname, aes(x = dur, y = rt)) +
  geom_point() +
  coord_trans(x = "log", y = "log")

Flip The Coordinates

  • data
  • aesthetics
  • geometries
  • facets
  • statistics
  • coordinates

ggplot(d_spellname, aes(x = dur, y = rt)) +
  geom_point() +
  coord_flip()

Add A Theme

  • data
  • aesthetics
  • geometries
  • facets
  • statistics
  • coordinates
  • theme

ggplot(d_spellname, aes(x = dur, y = rt)) +
  geom_point() +
  theme_dark()

Adjust One Theme Element

  • data
  • aesthetics
  • geometries
  • facets
  • statistics
  • coordinates
  • theme

ggplot(d_spellname, aes(x = dur, y = rt)) +
  geom_point() +
  theme(panel.background = element_blank())

Exercise 1: Build A Plot Layer By Layer

Complete RMarkdown document 01_building_ggplot_layers.Rmd.

This exercise practises reading a plot as a sequence of ggplot2 layers.

Read The Code As Layers

ggplot(data = d_spellname, 
       mapping = aes(x = dur, 
                     y = rt, 
                     colour = group)) +
  geom_point(size = .75) +
  stat_smooth(method = "lm", se = F) +
  labs(x = "Response duration (in ms)",
       y = "Reaction time (in ms)") +
  theme(legend.position = "right",
       legend.justification = "top",
       legend.direction = "vertical") 

Mapping Variables And Setting Styles

Mapping Versus Setting

Aesthetics: visual properties mapped to variables (data-driven) e.g. aes(x = duration, y = time, colour = group) → colour changes with data and usually creates a scale / legend

Attributes: visual properties set manually (constant) e.g. geom_point(colour = "blue", size = 2) → colour is fixed and does not describe a variable

Think:

Aesthetic = mapping (data → visual)

Attribute = setting (visual → fixed property)

Attribute: Set One Colour

  • appearance of geometries
  • e.g. colour, size, shape
  • attributes take properties
  • aesthetics take variables

ggplot(d_spellname, aes(x = dur, y = rt)) +
  geom_point(colour = "red")

Aesthetic: Map Colour To A Variable

  • appearance of geometries
  • e.g. colour, size, shape
  • attributes take properties
  • aesthetics take variables

ggplot(d_spellname, aes(x = dur, y = rt)) +
  geom_point(aes(colour = modality))

Mappings Can Affect Later Layers

  • appearance of geometries
  • e.g. colour, size, shape
  • attributes take properties
  • aesthetics take variables

ggplot(d_spellname, aes(x = dur, y = rt)) +
  geom_point(aes(colour = modality)) +
  stat_smooth(method = "lm")

Layer-Specific Mappings

  • appearance of geometries
  • e.g. colour, size, shape
  • attributes take properties
  • aesthetics take variables

ggplot(d_spellname, aes(x = dur, y = rt)) +
  geom_point() +
  stat_smooth(aes(colour = modality), method = "lm")

Repeating A Mapping Across Layers

  • appearance of geometries
  • e.g. colour, size, shape
  • attributes take properties
  • aesthetics take variables

ggplot(d_spellname, aes(x = dur, y = rt)) +
  geom_point(aes(colour = modality)) +
  stat_smooth(aes(colour = modality), method = "lm")

Global Mappings Apply To All Layers

  • appearance of geometries
  • e.g. colour, size, shape
  • attributes take properties
  • aesthetics take variables

ggplot(d_spellname, aes(x = dur, y = rt, colour = modality)) +
  geom_point() +
  stat_smooth(method = "lm")

Shape Can Encode Groups

ggplot(d_spellname, aes(x = dur, y = rt, shape = modality)) +
  geom_point(size = 2.5, colour = "red") 

Colour Can Encode Groups

ggplot(d_spellname, aes(x = dur, y = rt, colour = modality)) +
  geom_point(size = 2.5)

Avoid Overloading A Plot

ggplot(d_spellname, 
       aes(x = dur, y = rt, colour = modality)) +
  geom_point(size = 2.5)

Use one main aesthetic when it answers the question clearly.

  • Colour, shape, size, and labels all compete for attention.
  • Add another aesthetic only when it improves comparison or accessibility.
  • More encodings do not automatically make a plot more informative.

Use Redundant Coding Carefully

ggplot(d_spellname, aes(x = dur, y = rt,
                        colour = modality,
                        shape = modality)) +
  geom_point(size = 2.5)

Sometimes redundant coding is helpful:

  • colour helps quick grouping
  • shape can help when printed in greyscale
  • two groups are still manageable

Avoid this when it creates too many visual groups.

Common Aesthetics To Recognise

  • some are required by geometries; others are optional
  • continuous vs discrete variables:
    • e.g. shape and label can only be used for categorical values
  • should be chosen to facilitate comprehension
  • scatterplot: geom_point()
x, y, shape, colour, fill, size, alpha, stroke, group
  • barplot: geom_bar()
x, y, colour, fill, linewidth, linetype, alpha, width, group
  • boxplot: geom_boxplot()
x, y, lower, xlower, upper, xupper, middle, xmiddle, ymin, 
xmin, ymax, xmax, weight, colour, fill, size, alpha, shape, 
linetype, linewidth, width, group

Exercise 2: Aesthetics And Attributes

Complete RMarkdown document 02_aesthetics_vs_attributes.Rmd.

This exercise practises deciding whether a visual property should be mapped to a variable or set to a fixed value.

Variable Type Matters

Before mapping a variable to colour, shape, size, or another aesthetic, ask what kind of variable it is.

Variable type Examples Usually works well with
Continuous age, reaction time, vocabulary score position, gradients, sometimes size
Categorical modality, group, condition position, colour hue, shape, linetype, facets

For today, focus on where aesthetics go in the code. We will use variable type more directly next week when choosing plot types.

Check Your Mappings

If time permits, revisit your plots and ask whether each aesthetic improves the comparison.

Use the two exercise files from today as your main practice for Week 3.

Recommended Reading

Homework

Identify a dataset you would like to use for the formative assessment: post a description on our Teams channel.

Think about what you would like to visualise about these data:

  • Combination of variables
  • Variable types and appropriate aesthetics
  • Raw data and / or summary statistics
  • Look for appropriate visualisation tools HERE

References

Andrews, M. (2021). Doing data science in R: An introduction for Social Scientists. SAGE Publications Ltd.

Wickham, H. (2010). A layered grammar of graphics. Journal of Computational and Graphical Statistics, 19(1), 3–28.

Wickham, H. (2016). ggplot2: Elegant graphics for data analysis. Springer.

Wickham, H., & Grolemund, G. (2016). R for data science: Import, tidy, transform, visualize, and model data. O’Reilly Media, Inc.

Wilkinson, L. (2005). The grammar of graphics (2nd ed.). Springer.