R Programming / Analysis interfaces and table integrity / Lesson 9
Base graphics and honest scales
Choose plot encodings from the data question and verify the numbers behind the picture.
On this page
Lesson goals
- Match points, lines, and bars to data meaning.
- Explain axis limits, transformations, and missing observations.
- Keep plot state and export assumptions explicit.
Choose the comparison before drawing the plot
A scatterplot compares paired numeric coordinates, a line implies a meaningful ordering and connection, and a bar chart compares quantities associated with categories. A histogram groups numeric observations into intervals and is not simply a bar chart of arbitrary labels. Begin with the question and unit of observation. Preserve the same pairing and selection rules used in numerical summaries. Plotting an unsorted time sequence as a line can connect the wrong events, while drawing a line through unordered categories can imply a continuity the data do not possess. The visual encoding is part of the analytical argument.
Validate coordinates and labels independently
The first fixture checks equal lengths and finite coordinates and prints their ranges before showing an illustrative plot call in a comment. Clear axis labels state units or meaning rather than relying on a variableโs short name. Choose symbols and contrast that remain readable without color alone, and avoid plotting so many overlapping points that density disappears. A relevant jitter or transparency policy should be declared because it changes the display. The course does not open a graphics device or generate an image; the range calculation supplies a small reviewable numerical contract for the intended plot.
x <- c(1, 2, 3)
y <- c(2, 5, 4)
stopifnot(length(x) == length(y), all(is.finite(x)), all(is.finite(y)))
cat("x range=", paste(range(x), collapse = ","), "\n", sep = "")
cat("y range=", paste(range(y), collapse = ","), "\n", sep = "")
# Illustrative graphics call; requires an R graphics device.
# plot(x, y, type = "p", xlab = "Step", ylab = "Synthetic score", pch = 16)
x range=1,3
y range=2,5
Coordinate validation is separate from the commented graphics call; no plot or graphics device was executed during review.
Scales can amplify or suppress a difference
A truncated axis can make a small difference look dramatic, while an excessively broad scale can hide relevant variation. Bar lengths are usually read from a common baseline, so a nonzero baseline needs particular care. Logarithmic axes compare multiplicative changes and cannot directly represent nonpositive observations under ordinary log scaling. State what was excluded or transformed. Shared limits help compare panels, but only when their quantities and units are comparable. An axis choice should support the question honestly rather than maximize the visual impression of a preferred conclusion.
Verify the data that produce a category chart
The second fixture explicitly builds counts over four declared categories, including an unobserved category with zero count. It also calculates proportions under one denominator. A chart titled count should not quietly show percentages, and a proportion denominator should identify which observations were included. Missing values, weighted observations, and multiple responses can change that denominator. Keep the numeric table beside the plotting logic so reviewers can check totals and category coverage. A polished graphic cannot repair a wrong join, missing category, or duplicated observation introduced earlier in the pipeline.
values <- c(1, 1, 2, 4)
counts <- table(factor(values, levels = 1:4))
cat("counts=", paste(as.integer(counts), collapse = ","), "\n", sep = "")
cat("proportions=", paste(as.numeric(counts)/sum(counts), collapse = ","), "\n", sep = "")
# barplot(counts, xlab = "Synthetic category", ylab = "Count")
counts=2,1,0,1
proportions=0.5,0.25,0,0.25
The chart data retain a zero-count category and distinguish counts from proportions; the graphics call is illustrative only.
Graphics devices and state are explicit resources
Base graphics use a current device and parameters that can persist across plotting calls. Layout, margins, and axis settings can therefore influence later figures in an interactive session. A reusable plotting function should preserve and restore settings it changes, and a file-export function should close its own device even if plotting fails. Device support, fonts, dimensions, and resolution can affect output, so record them when sharing an artifact. Later lessons discuss cleanup patterns. These examples contain commented graphics calls and derived text output only; no rendering, export, font, or device behavior was tested in R.
Common errors and fixes
A line chart implies an incorrect trend
- Why it happens
- Rows were not ordered by the meaningful x variable or categories were connected arbitrarily.
- How to fix it
- Sort paired observations appropriately or choose an unconnected encoding.
- Prevent it next time
- State whether order and interpolation have a domain meaning.
A percentage chart changes after dropping missing rows
- Why it happens
- The denominator was implicit.
- How to fix it
- Define and report the eligible observation count.
- Prevent it next time
- Check category counts and proportions before drawing.
A later plot inherits an unexpected layout
- Why it happens
- Persistent graphics parameters were changed without restoration.
- How to fix it
- Save and restore the settings owned by the function.
- Prevent it next time
- Test plotting functions in a clean session and document device assumptions.
Check your understanding
1. Why should counts 2,1,0,1 retain the zero category when comparing periods?
Show worked solution
The shared vocabulary may require all four categories, even when one is absent in a period. Retaining it keeps axis alignment and makes absence visible. If a different vocabulary is intended, state it explicitly rather than letting observed data determine incomparable axes automatically.
2. A measurement can be zero. What should happen before selecting a logarithmic y axis?
Show worked solution
Inspect how many observations are nonpositive and why. Ordinary logarithmic coordinates do not represent zero. Choose a justified alternative scale or transformation with a clear label, or state an exclusion policy and its effect; do not silently delete inconvenient observations to obtain the desired plot.
Key takeaways
- The encoding should answer a stated comparison.
- Verify chart data, units, counts, and denominators.
- Graphics state and device behavior require their own checks.