← All resources

Agent skill

Visualization

Use when producing publication-ready R + ggplot2 figures for papers or slides. Applies perceptual chart selection; brand, subject-identity, magnitude, and CVD-safe palettes; Lora/Newsreader typography; direct labeling; uncertainty; one standalone panel per script; conditional LaTeX multi-panel assembly; PDF-only export; and a blocking inspection at intended placement size. Enforces sorted categories, plot-differences-not-raw, explicit units and aggregation, no gridlines, no explanatory titles or captions inside the image, and no clipping or overlap. For regression tables, use the tables skill.


Plan before rendering

For a new figure or substantial redesign, use the separate Retriever, Planner, Stylist, Visualizer and Critic agents defined in figure planning and revision. That guide owns dispatch, shared specifications, independent review and repair loops. Small edits activate only the relevant roles. Start retrieval with the rendered gallery and runnable source; use recipes for additional patterns.

Contents

  1. Standards — the 13 rules every figure must obey
  2. Perception — Cleveland-McGill, channel budget, layer-and-highlight
  3. Decisions — pick the chart type, name the color job
  4. Setup — shared theme, title, save, and palette helpers
  5. Palette rules — the color constraints that apply to every figure
  6. References — annotations, palettes, and implementation recipes
  7. Output — one standalone panel per file, conditional LaTeX assembly, PDF-only export
  8. Cross-references

1. Standards

  1. Tool: R + ggplot2. Default to ggplot2. Reach for matplotlib/seaborn only if the figure genuinely cannot be made in ggplot2.

  2. Sort categorical axes by value. No inherent order (countries, brands, models, conditions) → fct_reorder(var, value) (descending: .desc = TRUE). Alphabetical wastes the strongest pre-attentive channel — position. Exceptions: time, naturally-ordered categories (Likert, age bins), or a fixed external ordering that is itself the comparison.

  3. Value-axis range. For nonnegative values and interval endpoints, start at 0. Choose the upper limit from the largest plotted value or interval endpoint, with room for necessary annotations and readable, rounded ticks; values from 20 to 30 can use a 0–40 axis. Apply this to bounded and unbounded measures: percentages, shares, and Likert scores do not have to reach their theoretical cap. When values or intervals are negative, extend the lower limit below the minimum with similar headroom; values from −20 to 30 can use limits of −30 and 40. Limits need not be symmetric around zero. Signed differences and estimated effects, including event studies: include zero and the full confidence intervals. Use common limits across panels when their magnitudes are meant to be compared directly on the same scale. Apply the same rule to the numeric x-axis in horizontal value plots; time and categorical axes retain their natural domains. See the axis-limit recipe.

  4. Direct annotation by relevance. Label the subjects and groups needed to understand the comparison. When many subjects provide context, identify that background collectively instead of labeling every member. Horizontal-bar ticks may serve as labels. Suppress redundant guides; a compact key is allowed when direct group labels would be ambiguous. Read annotations.md for label selection and placement.

    Select observation labels deliberately. Label focal subjects, meaningful benchmarks, and outliers whose identity helps explain the pattern. Use a consistent selection rule, retain all plotted observations, and keep required labels visible. Outlier status alone does not require a label.

  5. Vector PDF output. Deliver vector PDFs only; do not generate companion PNG deliverables. Raster renders needed for inspection belong in exploratory/previews/ (see §7).

  6. Choose typography for the placement and surrounding document. For compact manuscript panels, start with 10–12 pt axis titles and 8–10 pt ticks and annotations, with facet strips slightly larger than ticks. Use larger sizes for slides or larger exhibits. These are starting ranges, not fixed requirements; verify readability and text/data balance in the assembled document. Keep Lora for titles and strips and Newsreader for ticks and annotations. The shared setup controls sizes; scale line widths, markers, and spacing accordingly.
    • Connected descriptive series: start around linewidth = 0.8 and point size = 2.5 for compact panels. Use lighter lines and fewer markers for dense paths, retaining the full line; see the series recipe. Keep markers proportionate to lines, ribbons light (alpha = 0.18–0.22), and reference lines subordinate.
    • Event studies and coefficient plots: use fine dots with individual intervals and theme_pub(style = "estimate"); follow the estimate recipe. Retain every estimated period and interval; descriptive-series marker thinning does not apply.
    • Dense scatterplots and background ensembles: choose smaller or lighter marks to preserve overlap patterns and readable focal marks; use the layer-and-highlight recipe. A connected-series marker-to-line ratio does not apply to independent observations.
  7. Keep categorical tick labels on one line. This is the default, especially for y-axis labels in horizontal bar and dot plots. Preserve required labels and readable type; use the axis-text fitting guidance, with wrapping only as a last resort under fixed placement constraints. For crowded numeric or date axes, thin ticks with scales::pretty_breaks(n = 6) or a wider date interval. Rotate only short standardized ticks such as dates; see recipes.md.

  8. Plot differences when the question is a contrast. Compute the gap (treatment − control) and plot one value per group, sorted by the difference. Two side-by-side bars force mental subtraction; the diff makes the comparison explicit. Distribution and concentration diagnostics instead show the relevant counts, shares, or levels.

  9. Calculate before you graph. Pre-aggregate with dplyr, plot with stat = "identity". Geom-side stats (after_stat(prop), stat_summary) fail in surprising ways with grouped/multi-variable aggregation; the summary table is itself a useful artifact.

  10. No explanatory text except direct data labels and designed annotations. Axis titles and tick labels are the only structural text inside the image; direct data labels and designed annotations from rule 4 are allowed. Do not set plot.title, plot.subtitle, plot.caption, or plot.tag; those belong in LaTeX (\caption{}, section prose, slide chrome) where they can be re-edited without re-rendering the figure. Notes, sample descriptions, model details, and any panel letter all live in TeX, not in the PDF.

    Use concise, sentence-case axis titles with plain-language quantity names. For DiD/event studies, name the time unit and event on x; default to the outcome name alone on y, such as Search visits or Employment. Put the coefficient scale, units, and routine aggregation in the caption or note. Follow the axis guidance for other chart types and the event-study guidance for wording and scale. Format ticks with scales::label_*; use y = NULL only when y ticks already name each item. Follow the three-layer unit-disclosure rule in annotations.md, which separates the axis label, LaTeX caption or panel subtitle, and figure note.

    Keep notes concise and self-contained. Follow the shared concise-note guidance, adapted from paper-writing: retain qualifications that change interpretation, credibility, or use; remove generic disclaimers, repeated caveats, and internal verification commentary. Use the caption, labels, and note together to explain the display. Put fuller methodological justification in methods and unresolved author questions outside the publication prose.

    For coefficient and heterogeneity plots, name the outcome and comparison dimension; avoid bare Change. Follow the coefficient-label guidance, preserving the outcome-only event-study axes above. Use the exhibit-title and TeX-panel guidance to divide wording across the shared title, panel subtitles, axes, and note, and the standalone-panel and LaTeX assembly rules for multi-panel figures.

  11. Show uncertainty for inferential estimates. For event studies, default to dots with individual intervals. Connecting lines are optional; choose their weight for readability at final placement. Select the uncertainty display separately from whether estimates are connected, preserving its statistical coverage. See the estimate recipe. Descriptive counts and shares of the observed sample need no automatic confidence intervals; disclose the sample and denominator.

    Describe inference in the TeX note. State what intervals or bands represent, their confidence level and pointwise or simultaneous coverage, the method, and clustering where used. For example, when supported: “Error bars show 95% pointwise confidence intervals; standard errors are clustered by firm.” Keep observation units separate from clustering units, and retain bootstrap details when applicable. Follow the shared inference-wording guidance; influence-score mechanics usually belong in methods.

  12. No gridlines. Drop both major and minor gridlines, panel border, and redundant ticks (Tufte taken further than the usual “faint major” compromise). The axis line + ticks carry value-lookup; keep ticks visible at placement size and use scales::pretty_breaks(n = 6–8) so the axis itself is the lookup aid. When a specific numeric value is part of the message — endpoint of a line, peak of a curve, a single bar — direct-label it with geom_text instead of asking the reader to interpolate against a grid. theme_pub() (§4) implements this.

  13. Blocking layout acceptance gate: nothing clips, touches, overlaps, or wastes space. A figure is not complete when ggsave() succeeds. It is complete only after the saved artifact has been opened and inspected at its intended manuscript or slide placement size.

    1. Declare geometry before constructing the plot. Set export width, export height, and intended placement width first with figure_spec(). Use the same physical unit for export and placement. Export width and placement width may differ by no more than 10%; do not export large and substantially shrink in LaTeX. Choose dimensions for the actual manuscript column or slide layout. For horizontal category plots, derive height from category count and row annotations, aiming for comparable physical row spacing across related panels. Different category counts may need different panel heights; align their quantitative axes in assembly. See the category geometry recipe.
    2. Save the PDF only. Use save_figure() to write the publication PDF with a white background. Do not export a companion PNG.
    3. Open the saved artifact itself. Inspect the saved PDF with a PDF-viewing or rendering tool, never only the RStudio plot pane. Save any required raster inspection renders in the project’s exploratory/previews/ directory, outside the delivery folder and excluded from version control. View the figure at the declared placement width. For TeX output, rebuild the report and inspect the placed figure in the report PDF too.
    4. Audit unit consistency. Verify that the code’s aggregation level, axis label, LaTeX caption or panel subtitle, surrounding prose, and figure note describe the same observation unit, population, and denominator. Never alternate casually among units such as languages, repositories, models, and foundation models. Separately verify that the note’s inference method, clustering dimensions, and interval coverage match the source. The clustering unit may differ from the observation unit; name it explicitly rather than substituting influence-score terminology.
    5. Verify content and balance after styling, then reject failures. Compare the plotted data and mappings with the prepared source: values, signs, series identities, transformations, intervals, population, denominator, and reference period must remain correct. Check for dropped or duplicated observations/series and clipped uncertainty. Read plotted values from the data or plot object, not by estimating pixels. Check categorical labels against rule 7. Reject cropped, touching, overlapping, or truncated text and incomplete guides. Inspect the balance between category labels, data, and annotations: reject avoidable gutters or excessive height that materially compress the data display, even when nothing overlaps. Compare with an approved reference figure when available.
    6. Repair by text role. Follow the collision-repair guidance, adjusting typography within rule 6’s readable range and preserving the data area. Reinspect the saved artifact and assembled document after repairs; eliminating overlap alone does not establish a good layout.
    7. Report only the verified state. If the saved artifact cannot be visually inspected, report it as generated but layout-unverified. Use the shared workflow for revision acceptance, stopping and review status.

    Use annotations.md and the relevant recipe for direct-label rails, off-panel annotations, wrapping, and collision repairs; keep their overflow protections when adapting them.


2. Perception

Cleveland-McGill — accuracy of perceptual tasks (best → worst)

  1. Position on a common scale (bar/dot, shared baseline)
  2. Position on non-aligned scales (small multiples)
  3. Length without baseline
  4. Angle / slope (pie, dual-axis)
  5. Area (bubble, treemap)
  6. Color luminance / saturation
  7. Color hue
  8. Volume / 3D

Default to bars or dot plots for quantitative comparison. Never pie, donut, 3D. Use area only when the message is “rough magnitude,” not precise comparison.

Channels for unordered categories (best → worst)

Spatial region (facet) → color hue → motion → shape. Reserve hue for the categorical distinction; shape is the default redundant channel — map it to the same variable as hue so the figure survives grayscale and colorblindness. Never map shape to a second variable.

Channel budget

Color and luminance pop pre-attentively; shape, angle, size do not. Hard rule: at most one variable encoded beyond position. If you find yourself mapping two different variables to color + shape (color = platform, shape = country), facet instead.

Redundant encoding is exempt — and is the default for multi-series lines. Mapping the same variable to both color and shape (ChatGPT = blue and circle) is one variable shown twice, not two channels of information; it does not spend the budget. It buys grayscale/B&W survival, colorblind safety, and disambiguation where two lines cross (the marker still names the series at the touch point). For 3–5 equal-weight line+point series, do this by default (§5).

Gestalt — connection and proximity dominate color similarity

Items linked by a line read as a group even if differently colored. Use deliberately (group structure via spacing/lines); avoid accidentally (don’t let layout suggest groupings the data doesn’t support).

Layer-and-highlight pattern

For “this country/firm/domain vs. all others”, use the emphasis hierarchy: light gray context, dark gray comparison when needed, and dark blue focal marks. Draw context first and focal marks last; identify dense background subjects collectively. Existing subject colors take precedence. Use the layer-and-highlight recipe and the selective-label rules in references/annotations.md.


3. Decisions

Chart type

Relationship Chart
Distribution (one var) Histogram, density, violin
Distribution (compare groups) Ridge, overlaid density
Two continuous vars Scatter, hexbin (large N)
Joint distribution / concentration across two ranked variables Joint quantile grid: 3×3, 5×5, 10×10, or another supported resolution
Category vs. continuous Bar/dot (mean ± CI), strip + box
Descriptive time series Line; add uncertainty only when applicable
DiD / event study Fine dots + individual intervals; quiet zero and event references
Time series + fitted models Black raw line + linetype-distinguished fits + grey CI
Correlation matrix Heatmap
Causal estimate Coefficient plot (dot + CI)
Geographic Choropleth

Color job

Name what color is for before picking a palette.

Job When Palette
Identification Treatment vs. control series_palette() by geometry: deeper marks, muted areas; see palettes
Magnitude (rank) Sorted bars colored by tertile Brand sequential ramp (brand_blues); subject_ramp() if the figure is about one subject
Magnitude (precise) Choropleth, heatmap, density Viridis
Signed deviation Coefficient vs. baseline, residual Diverging
Emphasis “ChatGPT vs. all platforms” emphasis: blue focal marks + gray comparison/context, or the focal subject’s fixed color

4. Setup

The theme function, title wrappers, figure specification/save helpers, brand palette, sequential ramp, and global ggplot defaults all live in scripts/theme_pub.R. Source it from the project’s one shared _setup.R (see “One script per panel” below) — don’t copy-paste or fork these definitions, because improvements to the central skill do not propagate into local copies.

library(ggplot2)
library(dplyr)
library(forcats)
library(ggrepel)
library(scales)
# Note: no patchwork — one standalone panel per file; combine only in LaTeX when warranted.

source("~/.claude/skills/visualization/scripts/theme_pub.R")

# Choose tick/annotation size in points for the intended placement.
label_pt <- 9
theme_set(theme_pub(base_size = label_pt))

# If Newsreader / Lora aren't installed system-wide, register them per session:
sysfonts::font_add_google("Newsreader", "Newsreader")
sysfonts::font_add_google("Lora",       "Lora")
showtext::showtext_auto()

This loads theme_pub(), labs_pub(), figure_spec(), save_figure(), palette helpers, and discrete color defaults. theme_pub() defaults to base_size = 9 for ticks, with axis titles at 1.25 times that size and facet strips at 1.125 times; it scales axis weights and margins with the type. Select a larger base for slides or large exhibits, such as 16, and inspect the actual placement. Pass the chosen base_size = label_pt whenever adding a gutter or style override, for example theme_pub(style = "estimate", base_size = label_pt). Text geoms need size = label_pt / ggplot2::.pt and family = "Newsreader" explicitly; their sizes and data-mark weights are not set by the theme. Adjust individual theme elements if the document needs a different hierarchy.

One script per panel

One runnable script per panel. Each standalone figure or report panel is produced by its own self-contained script (e.g. figures/fig_<slug>.R) that writes exactly one PDF. Never put several panels in one serial script — that forces them to render one after another.

One shared project setup, not divergent local copies. Factor the common preamble — the library() calls, the single source(".../theme_pub.R"), the showtext font registration above, project subject mappings, and any shared data prep — into one project-level _setup.R that every figure script sources. Do not redefine theme_pub(), labs_pub(), figure_spec(), or save_figure() in project/subproject setup files. When divergent copies already exist, replace them with thin forwarding setup files that source the one project helper; merely improving the central skill will not update copied functions. Cache expensive data prep to disk (e.g. saveRDS() / readRDS()) so each job reads the prepared data instead of recomputing it.

# figures/fig_referral_share.R
source("_setup.R")                 # theme + fonts + palette + cached data
spec <- figure_spec(
  stem = "fig_referral_share",
  width = 4.5, height = 3.3,
  placement_width = 4.5
)
dat <- readRDS("_cache/panel.rds")
# ... build p ...
save_figure(p, spec)

Because each script is independent, panels can render simultaneously under any parallel launcher: one panel = one PDF = one script = one job.

Greek and math symbols. Use Unicode directly in labels: α, β, μ, σ², ≥, ×. Symbol-font glyphs tofu in modern PDF readers.


5. Palette rules


6. References


7. Output

Inspection previews. Use project-root exploratory/previews/ for disposable raster renders of saved PDFs, creating it when inspection needs a raster image. Add /exploratory/previews/ to the project’s .gitignore. Keep this directory outside the delivery folder; previews are not deliverables. Keep exploratory analysis scripts and useful working figures elsewhere so they are not treated as disposable previews. save_figure() continues to write only the PDF; render previews separately only when needed for inspection.

One standalone panel per file. No patchwork, no plot_annotation(tag_levels = "A"), and no in-R panel combining. Each panel gets its own script and PDF. A faceted plot that forms one small-multiple encoding over a shared variable remains one panel. Combine panels in LaTeX under one figure number only when they jointly establish one argument and use compatible units, populations, and denominators; otherwise give each panel its own figure float.

Apply rule 13’s acceptance checks to every export and its final placement.

Use the PDF-export and TeX-placement examples in recipes.md.

Panel layout

Use rows × columns notation. For panels that meet the combination rule above, default to 1 × 2 (two panels side by side) or 2 × 2 (four panels in a grid) to save page space and make comparisons easy. Prefer these layouts over 2 × 1; stack two panels only when a side-by-side arrangement cannot accommodate their axes, labels, or data detail at readable final size. Choose other panel counts by the argument and available space rather than adding panels just to fill a grid.

Assemble the independent PDFs in LaTeX with consistent panel widths, aligned plot areas where feasible, and modest, even gaps. Order panels left to right, then top to bottom; use rows or columns for meaningful comparison groups. Keep panel letters, short subtitles, and the shared caption in LaTeX. Size each export for its actual subfigure width, accounting for the gap between columns, and retain the export/placement tolerance in rule 13. Inspect the complete figure in the compiled document for readable text, balanced spacing, and page fit; repair crowded labels or geometry before falling back to a vertical stack.


8. Cross-references

For regression / descriptive tables (journal star cutoffs, booktabs, never-change-a-number), see tables/SKILL.md. When reporting findings back to the user, report carries the deliverable template — figures here are the artifact, the report explains them.