Run once in the R console:
install.packages(c("rmarkdown", "knitr", "ggplot2", "patchwork",
"viridisLite", "colorspace", "dplyr", "tibble"))
Use R 4.1 or later for the native pipe |>. Open the
file in RStudio and select Knit, or run:
rmarkdown::render("01_visualization_reasoning_perception_colour.Rmd")
# Omit the optional answer section; worked examples remain visible.
rmarkdown::render("01_visualization_reasoning_perception_colour.Rmd",
params = list(show_solutions = FALSE),
output_file = "01_visualization_reasoning_perception_colour_student.html")
Rendering requires Pandoc, normally supplied by RStudio. HTML is the intended output. When preparing your own graphics, include written interpretations and accessible data tables when exact values matter.
| Topic | Specific reading in Fundamentals of Data Visualization | Role in this module |
|---|---|---|
| Data–ink ratio | Chapter 23, especially §23.1–23.2: Balance the data and the context | Direct discussion of Tufte and the limits of removing context |
| Visual channels | Chapter 2, §2.1–2.2: Mapping data onto aesthetics | Terminology for mappings; supplemented by Cleveland and McGill |
| Distorted magnitudes | Chapter 17: The principle of proportional ink | Related principle, distinct from maximizing data–ink |
| Palette type | Chapter 4, §4.1–4.3: Color scales | Qualitative, sequential, diverging, and highlighting uses |
| Colour mistakes and accessibility | Chapter 19, §19.1–19.3: Common pitfalls of color use | Unnecessary colour, non-monotonic scales, colour-vision deficiency |
| Anscombe’s quartet | Supplement: Anscombe (1973) | Primary reading; no specific Wilke section is claimed here |
| Perceptual accuracy | Supplement: Cleveland and McGill (1984) | Primary source for elementary perceptual tasks |
A useful starting point is to ask what information a graph makes easy to compare. A graph maps variables to visual properties (aesthetics) such as position, length, size, shape or colour. These choices are not neutral.
For example, position along a common scale is usually easier to compare accurately than angles or areas. This is one reason a dot plot or bar chart can be preferable to a pie chart when the goal is to compare quantities.
A graph can help us discover:
But a graph does not by itself establish a sampling design, statistical uncertainty, or a causal mechanism.
When looking at a graph, use the following order:
This separation prevents a common mistake: jumping from a visual pattern directly to a causal story.
A graph can reveal information that a mean, variance, or correlation discards. Anscombe’s quartet demonstrates this loss of information; it is not itself an optical illusion or a test of perceptual accuracy.
a <- do.call(rbind, lapply(1:4, function(i) {
data.frame(set = factor(paste("Set", i), levels = paste("Set", 1:4)),
observation = seq_len(nrow(anscombe)),
x = anscombe[[paste0("x", i)]],
y = anscombe[[paste0("y", i)]])
}))
summary_table <- do.call(rbind, lapply(split(a, a$set), function(d) {
fit <- lm(y ~ x, data = d)
data.frame(n = nrow(d), mean_x = mean(d$x), mean_y = mean(d$y),
var_x = var(d$x), var_y = var(d$y), r = cor(d$x, d$y),
intercept = unname(coef(fit)[1]), slope = unname(coef(fit)[2]),
R_squared = summary(fit)$r.squared)
}))
knitr::kable(summary_table, digits = 3,
caption = "Sample variances use the denominator n - 1.")
| n | mean_x | mean_y | var_x | var_y | r | intercept | slope | R_squared | |
|---|---|---|---|---|---|---|---|---|---|
| Set 1 | 11 | 9 | 7.501 | 11 | 4.127 | 0.816 | 3.000 | 0.5 | 0.667 |
| Set 2 | 11 | 9 | 7.501 | 11 | 4.128 | 0.816 | 3.001 | 0.5 | 0.666 |
| Set 3 | 11 | 9 | 7.500 | 11 | 4.123 | 0.816 | 3.002 | 0.5 | 0.666 |
| Set 4 | 11 | 9 | 7.501 | 11 | 4.123 | 0.817 | 3.002 | 0.5 | 0.667 |
The summaries are approximately equal, allowing for rounding of the original observations. Before plotting, sketch what you think each dataset could look like. Does a correlation near 0.82 establish a linear relationship?
ggplot(a, aes(x, y)) +
geom_point(size = 2.5, colour = "#0072B2") +
geom_smooth(method = "lm", formula = y ~ x, se = FALSE,
colour = "#D55E00", linewidth = .7) +
facet_wrap(~set, ncol = 2) +
coord_cartesian(xlim = c(3, 20), ylim = c(2, 14)) +
labs(x = "x", y = "y")
Anscombe’s quartet, with identical axis limits and separate least-squares fits.
These descriptions concern the displayed data. They do not justify causal conclusions or automatic deletion of unusual observations. Investigate measurement, sampling, and the scientific question first.
a_diag <- do.call(rbind, lapply(split(a, a$set), function(d) {
fit <- lm(y ~ x, data = d)
d$residual <- residuals(fit)
d$leverage <- hatvalues(fit)
d
}))
ggplot(a_diag, aes(x, residual)) + geom_hline(yintercept = 0, colour = "grey60") +
geom_point(size = 2) + facet_wrap(~set) +
labs(y = "Observed y - fitted y")
Residuals expose curvature and unusual departures hidden by the common summaries.
For simple regression with an intercept,
\[ h_{ii}=\frac{1}{n}+\frac{(x_i-\bar{x})^2}{\sum_j(x_j-\bar{x})^2}. \]
The isolated x value in Set 4 has leverage one. Its fitted residual is zero even though it determines the slope: a small residual does not imply an unimportant observation.
d4 <- subset(a_diag, set == "Set 4")
knitr::kable(d4[, c("observation", "x", "y", "residual", "leverage")], digits = 3)
| observation | x | y | residual | leverage | |
|---|---|---|---|---|---|
| Set 4.34 | 1 | 8 | 6.58 | -0.421 | 0.1 |
| Set 4.35 | 2 | 8 | 5.76 | -1.241 | 0.1 |
| Set 4.36 | 3 | 8 | 7.71 | 0.709 | 0.1 |
| Set 4.37 | 4 | 8 | 8.84 | 1.839 | 0.1 |
| Set 4.38 | 5 | 8 | 8.47 | 1.469 | 0.1 |
| Set 4.39 | 6 | 8 | 7.04 | 0.039 | 0.1 |
| Set 4.40 | 7 | 8 | 5.25 | -1.751 | 0.1 |
| Set 4.41 | 8 | 19 | 12.50 | 0.000 | 1.0 |
| Set 4.42 | 9 | 8 | 5.56 | -1.441 | 0.1 |
| Set 4.43 | 10 | 8 | 7.91 | 0.909 | 0.1 |
| Set 4.44 | 11 | 8 | 6.89 | -0.111 | 0.1 |
# If this observation is omitted, all remaining x values are equal.
isolated <- which.max(d4$x)
fit_without <- lm(y ~ x, data = d4[-isolated, ])
coef(fit_without) # slope is NA: it is no longer identifiable
## (Intercept) x
## 7.001 NA
Consider the following questions individually, then compare your answers with a partner:
An unusual observation is a statistical signal, not automatically a mistake. Possible explanations include:
A useful workflow is:
The phrase “remove the outlier because it looks strange” is not a statistical justification.
A useful distinction is between exploratory and explanatory graphics. The difference is not mainly aesthetic: it concerns the purpose of the graph and the audience for whom it is produced.
An exploratory graphic is primarily a tool for the analyst. Its purpose is to help us ask questions about the data:
At this stage, it is perfectly reasonable to produce many graphs, try alternative scales, add smoothers, facet by different variables, or inspect individual observations. Some of these graphs may never appear in the final report. Their role is to support statistical discovery rather than communication.
An explanatory graphic, in contrast, is designed for an audience. By the time we construct it, we usually have a clearer idea of which feature of the data matters. The purpose is no longer simply to discover patterns, but to make an important comparison or result easy to see.
The same dataset may therefore generate many exploratory graphics but only one or two explanatory graphics.
A useful way to think about the distinction is:
Exploration asks: “What can I learn from these data?”
Explanation asks: “What should my audience notice in these data?”
Importantly, explanatory graphics should not hide relevant complexity or uncertainty. Simplification means removing visual elements that are not useful for the intended comparison, not removing observations or evidence that contradicts the desired message.
Suppose we are interested in the relationship between automobile weight and fuel economy. We might begin with a simple scatterplot and a fitted linear trend.
cars <- mtcars |>
as_tibble(rownames = "car")
ggplot(cars, aes(wt, mpg)) +
geom_point(size = 3) +
geom_smooth(method = "lm", se = FALSE) +
labs(
title = "Exploring the relationship between weight and fuel economy",
x = "Weight (1000 lb)",
y = "Miles per gallon"
)
At this stage, the graph is a tool for asking questions. The negative association is immediately visible, but we should not stop at the fitted line.
For example, we might ask whether the relationship differs according to the number of cylinders:
cars |>
mutate(cyl = factor(cyl)) |>
ggplot(aes(wt, mpg, colour = cyl)) +
geom_point(size = 3) +
geom_smooth(method = "lm", se = FALSE) +
labs(
title = "Does the relationship differ by cylinder count?",
x = "Weight (1000 lb)",
y = "Miles per gallon",
colour = "Cylinders"
)
Or we could separate the groups into panels:
cars |>
mutate(cyl = factor(cyl)) |>
ggplot(aes(wt, mpg)) +
geom_point(size = 3) +
geom_smooth(method = "lm", se = FALSE) +
facet_wrap(~ cyl) +
labs(
title = "Weight and fuel economy within cylinder groups",
x = "Weight (1000 lb)",
y = "Miles per gallon"
)
These different views answer slightly different questions. The first emphasises the overall relationship, while the second and third encourage us to consider whether part of that relationship might reflect differences between groups.
This is an important feature of exploratory analysis: one graph often leads to another question and therefore to another graph.
The fitted regression line summarises the relationship between
wt and mpg. It helps us see the overall
direction and strength of the linear association.
However, the line should not be confused with the data themselves. Individual observations may lie far from it, and a fitted line may hide nonlinear patterns, clusters, or influential observations.
Moreover, the fitted relationship is associational. From this graph alone we cannot conclude that changing the weight of a car would cause a corresponding change in fuel economy. Other characteristics, such as engine size, number of cylinders, vehicle design, and transmission type, may be related to both variables.
Thus a smoother or regression line is a model-based visual summary, not a causal statement.
After exploring the data, suppose we decide that the main message we want to communicate is:
Heavier cars tend to have lower fuel economy.
An explanatory graphic can make this comparison more explicit.
selected_cars <- cars |>
filter(
car %in% c(
"Toyota Corolla",
"Cadillac Fleetwood",
"Ferrari Dino"
)
)
ggplot(cars, aes(wt, mpg)) +
geom_point(alpha = 0.45, size = 3) +
geom_smooth(method = "lm", se = FALSE) +
geom_text(
data = selected_cars,
aes(label = car),
nudge_y = 1.5,
check_overlap = TRUE
) +
labs(
title = "Heavier cars tend to have lower fuel economy",
subtitle = "The fitted line summarises an association, not a causal effect",
x = "Weight (1000 lb)",
y = "Miles per gallon",
caption = "Data: mtcars"
)
Notice how the role of the title has changed. In the exploratory graph the title describes what we are investigating:
Exploring the relationship between weight and fuel economy.
In the explanatory graph the title communicates the principal finding:
Heavier cars tend to have lower fuel economy.
A few observations are labelled because they provide useful reference points. Labelling every car would make the display harder to read and would distract from the main comparison.
This illustrates an important principle of explanatory visualisation:
Emphasise what matters, de-emphasise what does not, but do not distort the evidence.
Exploratory visualisation rarely follows a straight path. A realistic workflow might look like this:
question → graph → unexpected feature → new question → new graph
For example:
wt against mpg.cyl.Graphs therefore participate directly in statistical reasoning. They are not simply illustrations produced after the analysis has been completed.
Because exploratory and explanatory graphics have different purposes, they can also be judged by somewhat different criteria.
An exploratory graph is useful if it helps the analyst:
An explanatory graph is useful if it helps the reader:
A graph can therefore be excellent for exploration but poor for presentation. A dense matrix of twenty plots may be extremely useful to an analyst investigating a dataset, but inappropriate in a report whose audience needs to understand one particular result.
Conversely, a highly simplified explanatory graphic may be ideal for communication but insufficient for diagnosing whether the underlying statistical model is appropriate.
The two types of graphics are therefore complementary rather than competing:
Explore broadly; explain selectively.
A scatterplot can show association. It cannot, by itself, demonstrate causality.
ggplot(mtcars, aes(hp, mpg)) +
geom_point(size = 3) +
labs(
title = "Horsepower and fuel economy are negatively associated",
subtitle = "The plot alone does not identify a causal effect",
x = "Horsepower",
y = "Miles per gallon"
)
Possible reasons for an association include:
The distinction is particularly important when a graph is used to communicate results from observational data.
A reproducible graphic records the data, mappings, geometric objects and transformations used to produce it.
The basic ggplot2 structure is:
ggplot(data, aes(x = ..., y = ...)) +
geom_...
Think of the components as separate decisions:
A visual encoding should support the comparison the reader needs to make. Common choices include:
| Goal | Often useful | Potential problem |
|---|---|---|
| Compare quantities | position, length | truncated axes can exaggerate differences |
| Show a distribution | histogram, density, boxplot | bin width/bandwidth changes the apparent shape |
| Show a relationship | scatterplot | overplotting can hide observations |
| Show a time trend | line plot | connecting unrelated observations can imply continuity |
| Compare groups | aligned positions, facets | too many colours/categories reduce readability |
A bar chart whose vertical axis does not start at zero can make differences in length appear much larger than they are. For points, however, forcing an axis to start at zero is not generally necessary: the important comparison is often the relative position of the observations.
The statistical question should determine the scale, rather than a mechanical rule such as “every axis must start at zero.”
comparison <- tibble(
group = c("A", "B", "C"),
estimate = c(72, 75, 77)
)
p_scale <- ggplot(comparison, aes(group, estimate)) +
geom_col(fill = "#0072B2") +
labs(x = "Group", y = "Estimated score")
(p_scale + labs(title = "Bars from zero")) +
(p_scale + coord_cartesian(ylim = c(70, 79)) +
labs(title = "Truncated bars exaggerate ratios"))
Now compare the same information as points:
ggplot(comparison, aes(group, estimate)) +
geom_point(size = 4) +
coord_cartesian(ylim = c(70, 79)) +
labs(y = "Estimated score")
The truncated bar chart makes visible bar lengths proportional to distance above 70 rather than to the full scores. The dot plot can use this narrower range because position, rather than bar length from a baseline, carries the comparison. Keep axis labels visible and explain the scale; the geometry and scale should serve the intended question.
A channel is a visual property that carries information, such as position, length, area, or colour. Wilke calls these properties aesthetics. Cleveland and McGill studied the elementary comparisons viewers make when decoding graphs.
Their proposed ordering, from generally more accurate to less accurate quantitative judgments, can be summarised as follows:
| Approximate tier | Task | Typical example |
|---|---|---|
| 1 | Position along a common scale | Aligned dots; bar endpoints |
| 2 | Position along identical but nonaligned scales | Separate panels requiring visual transfer |
| 3 | Length, direction, angle | Floating bar segments; line orientation; pie slices |
| 4 | Area | Bubble sizes |
| 5 | Volume, curvature | Three-dimensional symbols; curve shape comparisons |
| 6 | Shading or colour saturation | Magnitude inferred from shading |
This is a qualitative guide, not a universal ranking with fixed error rates. The paper combines theory and selected experiments; it does not establish every pairwise comparison in every display. Task, separation, aspect ratio, and visual context matter. Unordered hue is useful for identifying categories, but has no intrinsic numerical order.
Estimate the value for C as a percentage of the value for E, first from each graph without consulting its legend. Then inspect the underlying values.
measure <- data.frame(group = LETTERS[1:5], value = c(20, 35, 46, 63, 80))
pos <- ggplot(measure, aes(value, group)) + geom_point(size = 3) +
scale_x_continuous(limits = c(0, 90)) + labs(title = "Position", x = "Value", y = NULL)
area <- ggplot(measure, aes(1, group, size = value)) +
geom_point(colour = "#0072B2") + scale_size_area(max_size = 16, limits = c(0, 90)) +
scale_x_continuous(breaks = NULL) + labs(title = "Area", x = NULL, y = NULL) +
theme(legend.position = "none", panel.grid = element_blank())
col <- ggplot(measure, aes(1, group, fill = value)) + geom_tile(width = .7, height = .7) +
scale_fill_viridis_c(limits = c(0, 90), end = .9) +
scale_x_continuous(breaks = NULL) + labs(title = "Colour", x = NULL, y = NULL) +
theme(panel.grid = element_blank(), legend.position = "bottom")
pos + area + col
Position, area, and colour encode the same invented measurements.
100 * measure$value[measure$group == "C"] / measure$value[measure$group == "E"]
## [1] 57.5
The correct answer is 57.5%. These displays illustrate the comparison; they do not replicate the 1984 experiment: the axes and legends provide different reference information. A controlled study would also standardise those aids, randomise trials, and collect repeated judgments.
For precise comparisons, start by considering position. Area or colour can still be useful when position is already occupied by other variables, such as spatial coordinates in a map.
segments <- data.frame(group = rep(LETTERS[1:4], each = 2),
part = rep(c("Base", "Target"), 4),
count = c(20, 30, 60, 35, 35, 32, 50, 34))
segments$part <- factor(segments$part, levels = c("Base", "Target"))
p_stack <- ggplot(segments, aes(group, count, fill = part)) +
geom_col(position = position_stack(reverse = TRUE), width = .6) +
scale_fill_manual(values = c(Base = "grey80", Target = "#0072B2")) +
labs(title = "Compare the blue segments", y = "Count", x = NULL)
p_target <- ggplot(subset(segments, part == "Target"), aes(count, group)) +
geom_point(size = 3, colour = "#0072B2") +
scale_x_continuous(limits = c(0, 40)) +
labs(title = "Compare aligned positions", x = "Target count", y = NULL)
p_stack + p_target
The target segment has no common baseline in the stacked chart; the dot chart aligns target counts.
The stacked version answers a composition question and preserves totals. The dot chart answers a question specifically about Target. Do not declare one universally superior: identify what the reader needs to compare.
If the radius doubles, the area increases by a factor of four. To encode values 10 and 40 by circle area, use a radius ratio of two, not four:
\[ A=\pi r^2,\qquad A\propto v\ \Longrightarrow\ r\propto\sqrt{v}. \]
# Explicit polygon geometry avoids ambiguities about point-size conventions.
circle_data <- function(correct) {
do.call(rbind, lapply(1:2, function(i) {
v <- c(10, 40)[i]
r <- if (correct) .8 * sqrt(v / 40) else .8 * v / 40
theta <- seq(0, 2*pi, length.out = 200)
data.frame(x = 2*i + r*cos(theta), y = r*sin(theta), id = factor(v),
method = if (correct) "Area proportional to value" else "Radius proportional to value")
}))
}
circles <- rbind(circle_data(TRUE), circle_data(FALSE))
ggplot(circles, aes(x, y, group = id)) +
geom_polygon(fill = "#56B4E9", colour = "#0072B2") +
facet_wrap(~method) + coord_equal(xlim = c(1, 5), ylim = c(-1, 1)) +
scale_x_continuous(breaks = c(2, 4), labels = c("Value: 10", "Value: 40")) +
labs(x = NULL, y = NULL) +
theme(panel.grid = element_blank(), axis.text.y = element_blank(),
axis.ticks.y = element_blank())
A fourfold change in value should produce a fourfold area change, not a sixteenfold area change.
Tufte’s data–ink ratio is conceptually
\[ \text{data–ink ratio} =\frac{\text{ink used for non-redundant representation of data}} {\text{total ink in the graphic}}. \]
Treat this as an editing principle, not as a numerical score to optimise by counting pixels. A thick border may attract attention without helping interpretation; an axis label uses ink but identifies the measured quantity. The decision is whether an element serves the reader’s task.
Wilke’s Chapter 23 emphasises retaining enough context: removing all reference marks can make comparisons harder. Keep readable units, meaningful reference lines, and a clear mapping from marks to variables. Non-data ink is not synonymous with useless ink.
A different principle: proportional ink concerns whether the size of a mark faithfully represents magnitude. For circles with area proportional to a value \(v\), the radius must be proportional to \(\sqrt{v}\). This is different from deciding how much decoration to remove.
The following invented counts represent students attending six optional workshops. Before reading the code, consider these questions: Which plot lets you read the attendance at workshop D? Which lets you identify the largest attendance?
attendance <- data.frame(workshop = LETTERS[1:6],
students = c(24, 37, 29, 43, 34, 19))
p <- ggplot(attendance, aes(workshop, students)) +
geom_col(fill = "#0072B2", width = .65) +
scale_y_continuous(limits = c(0, 50), breaks = seq(0, 50, 10),
expand = expansion(mult = c(0, .02))) +
labs(x = "Workshop", y = "Number of students")
clutter <- p + labs(title = "Too much decoration") +
theme(panel.background = element_rect(fill = "grey85"),
panel.grid.major = element_line(colour = "grey35", linewidth = .8),
panel.grid.minor = element_line(colour = "grey55", linewidth = .5),
panel.border = element_rect(fill = NA, colour = "black", linewidth = 1.5),
plot.background = element_rect(fill = "grey95", colour = "black"))
balanced <- p + labs(title = "Useful context") +
theme(panel.grid.major.x = element_blank(), panel.grid.minor = element_blank())
empty <- p + theme_void(base_size = 12) + labs(title = "Too little context")
clutter + balanced + empty + plot_layout(nrow = 1)
Identical counts with excessive decoration, useful context, and insufficient context.
Interpretation. The last version still allows rough ranking, but the question about workshop D cannot be answered without labels. Adding direct values could help precise lookup; it would also introduce more ink. The task, rather than maximal simplicity, determines the choice.
Hue describes a colour family, such as blue or orange. Chroma describes departure from a neutral grey at a given lightness. Lightness describes how light or dark a colour appears relative to a reference white. Saturation is related to chroma but is not an interchangeable technical quantity across colour models.
RGB specifies display primaries; equal numerical RGB steps need not look equally different. Perceptual colour spaces are designed to better approximate visual differences. Even then, colour appearance depends on surrounding colours, mark size, display, and viewing conditions. A tiny pale point can disappear on white although the same colour works in a large tile.
| Variable or task | Palette | Example | Common mistake |
|---|---|---|---|
| Unordered categories | Qualitative | Species; study programme | Suggesting a rank with light-to-dark colours |
| Ordered magnitude | Sequential | Counts; density; elevation | A rainbow with no clear lightness order |
| Deviation around a reference | Diverging | Residuals around zero | A sequential palette that hides the reference |
| Emphasis | Neutral colours plus an accent | One selected group | Giving every item equal visual emphasis |
For diverging data, choose the midpoint from the scientific meaning, not automatically from the sample mean. For a signed effect, zero often has meaning. For differences across panels, preserve common scale limits.
The data below increase uniformly from left to right and do not change vertically. Any apparent bands beyond this smooth gradient come from the encoding or display.
field <- expand.grid(x = seq(0, 1, length.out = 200), y = seq(0, 1, length.out = 30))
field$value <- field$x
base_field <- ggplot(field, aes(x, y, fill = value)) + geom_raster() +
scale_y_continuous(breaks = NULL) + labs(x = "x", y = NULL, fill = "Value") +
theme(panel.grid = element_blank(), legend.position = "bottom")
rainbow_plot <- base_field +
scale_fill_gradientn(colours = rainbow(256), limits = c(0, 1)) + labs(title = "Rainbow")
viridis_plot <- base_field +
scale_fill_viridis_c(limits = c(0, 1)) + labs(title = "Viridis")
rainbow_plot + viridis_plot
A mathematically smooth field displayed with rainbow and viridis palettes.
Viridis and several related palettes are designed for approximately uniform perceptual progression and useful lightness ordering. They are practical choices for ordered numeric data, including under common colour-vision deficiencies. This is not a guarantee that any plot using them is accessible: mark size, contrast, scale limits, and non-colour cues still matter. Nor should every option offered by a palette package be assumed to share identical perceptual properties.
palette_names <- c("viridis", "magma", "inferno", "cividis")
strips <- do.call(rbind, lapply(palette_names, function(nm) {
data.frame(value = seq(0, 1, length.out = 100), palette = nm,
colour = viridisLite::viridis(100, option = nm))
}))
ggplot(strips, aes(value, palette, fill = colour)) + geom_tile() +
scale_fill_identity() + labs(x = "Normalised value", y = NULL) +
theme(panel.grid = element_blank())
Four sequential palettes with different hues but an ordered progression.
In ggplot2, use _c for continuous scales,
_d for discrete scales, and _b for binned
numeric scales. A discrete scale does not imply that the selected
colours are ideal for unordered groups; a lightness sequence can still
suggest an order.
ggplot(mtcars, aes(disp, mpg, colour = hp)) + geom_point(size = 3) +
scale_colour_viridis_c(option = "viridis", end = .9) +
labs(x = "Engine displacement (cubic inches)",
y = "Fuel economy (US miles per gallon)", colour = "Horsepower")
Position represents engine displacement and fuel economy; colour adds horsepower.
Here position supports reading the main relationship; colour adds a
third variable. The plot uses historical cars from R’s
mtcars dataset and is not representative of today’s car
market.
deviation <- expand.grid(row = factor(LETTERS[1:4]), column = factor(1:5))
deviation$effect <- rep(c(-3, -1.5, 0, 1.5, 3), each = 4)
ggplot(deviation, aes(column, row, fill = effect)) + geom_tile(colour = "white") +
geom_text(aes(label = effect), colour = "black", size = 4) +
scale_fill_gradient2(low = "#91BFDB", mid = "#F7F7F7", high = "#F4A582",
midpoint = 0, limits = c(-3, 3)) +
labs(x = "Condition", y = "Group", fill = "Deviation") + coord_equal() +
theme(panel.grid = element_blank())
Signed deviations use a diverging scale centred at zero.
The numbers make sign and magnitude available without relying on colour. This small example permits labels; a large matrix would need another way to provide exact values.
The colorspace package provides transformations
approximating different colour-vision deficiencies. A simulation is a
diagnostic aid, not a complete model of every person’s experience.
Grayscale is a separate check: colour-vision deficiency does not
generally mean seeing only grey.
transformations <- list(
Original = identity,
Deutan = function(z) colorspace::deutan(z, severity = 1),
Protan = function(z) colorspace::protan(z, severity = 1),
Tritan = function(z) colorspace::tritan(z, severity = 1),
Grayscale = function(z) colorspace::desaturate(z)
)
palettes <- list(Rainbow = rainbow(100), Viridis = viridisLite::viridis(100))
checks <- do.call(rbind, lapply(names(palettes), function(pn) {
do.call(rbind, lapply(names(transformations), function(tn) {
data.frame(value = seq(0, 1, length.out = 100), palette = pn,
view = tn, colour = transformations[[tn]](palettes[[pn]]))
}))
}))
checks$view <- factor(checks$view, levels = rev(names(transformations)))
ggplot(checks, aes(value, view, fill = colour)) + geom_tile() +
facet_wrap(~palette, ncol = 1) + scale_fill_identity() +
labs(x = "Normalised value", y = NULL) + theme(panel.grid = element_blank())
Original, simulated colour-vision deficiency, and grayscale views of rainbow and viridis.
Follow each row from left to right. Can you reliably infer increasing values? Which palette maintains a useful ordering after the transformation?
For unordered groups, combine a qualitative palette with shape, line type, or direct labels. The following invented trajectories deliberately combine colour and line type; endpoint labels further reduce legend lookup.
trajectories <- data.frame(time = rep(1:6, 3), group = rep(c("A", "B", "C"), each = 6),
response = c(2, 3, 4, 5, 6, 7,
7, 6.8, 6.5, 6.2, 5.8, 5.4,
3.5, 3.7, 3.8, 4, 4.1, 4.2))
qualitative <- c(A = "#0072B2", B = "#D55E00", C = "#009E73")
ggplot(trajectories, aes(time, response, colour = group, linetype = group)) +
geom_line(linewidth = .9) +
geom_text(data = subset(trajectories, time == 6),
aes(label = group), hjust = -.7, show.legend = FALSE) +
scale_colour_manual(values = qualitative) +
scale_linetype_manual(values = c(A = "solid", B = "dashed", C = "dotdash")) +
scale_x_continuous(limits = c(1, 6.7), breaks = 1:6) +
labs(x = "Time (weeks)", y = "Response (arbitrary units)") +
theme(legend.position = "none")
Group identity is carried by colour, line type, and direct labels.
Check the rendered figure at its intended display size. A dashed line needs sufficient length to reveal the dash pattern; a shape needs sufficient size to be identifiable. Accessibility also includes readable text, meaningful captions, alternative text, and an accessible table when exact values are needed.
Work in a group of 3–4 and allow approximately 20 minutes for this activity.
Choose a chart from a newspaper, website, report or social-media post. Do not spend time deciding whether the underlying scientific claim is true; focus first on the graphic as a statistical communication device.
Answer:
Prepare a 60-second explanation of your group’s redesign, linking your proposed change to the comparison the graph should support.
Suppose a university collects data on students’ study time and exam performance. The research question is:
“Is performance associated with the amount of time students report studying each week?”
Write down your design before writing code.
Specify:
Using mtcars as a practice dataset, create a scatterplot
answering the analogous question about wt and
mpg.
Your plot should include:
ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point() +
geom_smooth(method = "lm", se = FALSE) +
labs(
title = "...",
x = "...",
y = "..."
)
Of particular interest (to me):
https://clauswilke.com/dataviz/coordinate-systems-axes.html#nonlinear-axes
https://clauswilke.com/dataviz/visualizing-amounts.html
https://clauswilke.com/dataviz/histograms-density-plots.html#visualizing-a-single-distribution
https://clauswilke.com/dataviz/proportional-ink.html#visualizations-along-linear-axes
https://clauswilke.com/dataviz/color-pitfalls.html
?colorspace::simulate_cvd.The source file was structurally checked when prepared, but its R chunks were not executed in the preparation environment because R was unavailable. When you knit it, the following records your actual runtime and package versions.
sessionInfo()
## R version 4.6.1 (2026-06-24 ucrt)
## Platform: x86_64-w64-mingw32/x64
## Running under: Windows 11 x64 (build 26200)
##
## Matrix products: default
## LAPACK version 3.12.1
##
## locale:
## [1] LC_COLLATE=Italian_Italy.utf8 LC_CTYPE=Italian_Italy.utf8
## [3] LC_MONETARY=Italian_Italy.utf8 LC_NUMERIC=C
## [5] LC_TIME=Italian_Italy.utf8
##
## time zone: Europe/Rome
## tzcode source: internal
##
## attached base packages:
## [1] stats graphics grDevices utils datasets methods base
##
## other attached packages:
## [1] tibble_3.3.1 dplyr_1.2.1 patchwork_1.3.2 ggplot2_4.0.3
##
## loaded via a namespace (and not attached):
## [1] Matrix_1.7-5 gtable_0.3.6 jsonlite_2.0.0 compiler_4.6.1
## [5] tidyselect_1.2.1 jquerylib_0.1.4 splines_4.6.1 scales_1.4.0
## [9] yaml_2.3.12 fastmap_1.2.0 lattice_0.22-9 R6_2.6.1
## [13] labeling_0.4.3 generics_0.1.4 knitr_1.51 bslib_0.12.0
## [17] pillar_1.11.1 RColorBrewer_1.1-3 rlang_1.3.0 cachem_1.1.0
## [21] xfun_0.60 sass_0.4.10 S7_0.2.2 otel_0.2.0
## [25] viridisLite_0.4.3 cli_3.6.6 withr_3.0.3 magrittr_2.0.5
## [29] mgcv_1.9-4 digest_0.6.39 grid_4.6.1 rstudioapi_0.19.0
## [33] lifecycle_1.0.5 nlme_3.1-169 vctrs_0.7.3 evaluate_1.0.5
## [37] glue_1.8.1 farver_2.1.2 colorspace_2.1-3 rmarkdown_2.31
## [41] tools_4.6.1 pkgconfig_2.0.3 htmltools_0.5.9
Note on AI assistance
These teaching materials were prepared with assistance from ChatGPT (OpenAI) in drafting explanations, developing examples, and generating R code. The author retains responsibility for the final content.