Data Visualization with ggplot2

Build plots in R layer by layer with ggplot2. Learn the grammar of graphics behind every chart: map variables to aesthetics, choose geoms for distributions and relationships, and use the statistics and position adjustments behind bars, histograms, boxplots and trend lines. Split plots into facets, control axes, colors and legends with scales, and zoom or change the coordinate system. Finally, turn exploratory plots into clear figures with labels, annotations and themes, and save them at the right size or combine several into one layout.

IntermediateLesson 2 of 7 in Data Analysis with R Course

What you will learn

  1. Describe any plot as data, aesthetic mappings and layers, and write, store and debug the ggplot2 code that builds it one layer at a time.
    • Describe a plot as components of the grammar of graphics
      Name the components every ggplot2 plot is made of and read an existing chart as a combination of them.
    • Write, store and debug a ggplot2 call
      Write ggplot2 code with correct syntax, add layers in the right order, keep plots in objects, and use errors, warnings and messages to fix problems.
  2. Turn variables into visual properties, and pick the geoms that show the distribution of one variable or the relationship between several.
    • Map variables to aesthetics or set fixed values
      Distinguish mapping a variable inside aes() from setting a constant, and use color, fill, shape, size, alpha and group correctly.
    • Show the distribution of one variable
      Use bar charts for a categorical variable and histograms, density plots and frequency polygons for a numerical one, and choose a bin width that shows the shape.
    • Show relationships between two or more variables
      Pick geoms by the types of the variables, combine several geoms in one plot, and handle extra variables and overplotting.
  3. Understand the computation behind each geom, use the computed values, summarize groups with boxplots, summaries and smoothers, and arrange overlapping marks.
    • Work with the stat behind each geom
      Identify the default stat of a geom, choose between geom_bar and geom_col, and map computed variables with after_stat().
    • Summarize groups with boxplots, summaries and smoothers
      Read and build boxplots, plot group summaries with stat_summary(), and add and interpret trend lines with geom_smooth().
    • Arrange overlapping marks with position adjustments
      Choose between stacking, filling, dodging, identity, jittering and nudging for marks that share a position.
  4. Split plots into panels, control how data values become positions, colors and legends, and choose the coordinate system and zoom.
    • Split a plot into small multiples with facets
      Use facet_wrap() and facet_grid(), decide between shared and free scales, and judge when facets work better than color.
    • Control axes with position scales
      Set axis titles, breaks, labels, limits and expansion, use log and other transformations, and format numbers and dates.
    • Choose color scales and adjust legends
      Pick suitable discrete and continuous color scales, assign colors manually, and control legend position, titles and keys.
    • Zoom and choose the coordinate system
      Zoom without losing data, swap or fix axes, and use polar and transformed coordinates where they help.
  5. Turn an exploratory plot into a clear figure for others: informative labels, targeted annotations, a consistent look, and saved files at the right size, alone or combined.
    • Write labels and titles that explain the plot
      Use labs() to add a title that states the finding, a subtitle, a caption, axis and legend titles with units, math expressions and alt text.
    • Annotate points, lines and regions
      Label selected points with geom_text(), geom_label() or ggrepel, add single annotations with annotate(), and draw reference lines and highlighted regions.
    • Style a plot with themes
      Apply complete themes, change single theme elements with theme() and element functions, and set a consistent theme for a whole project.
    • Save plots and combine them into layouts
      Export plots with ggsave() at a chosen size, resolution and format, and combine several plots into one figure with patchwork.

Data Visualization with ggplot2 study guide

5 chapters

1

Build plots with the grammar of graphics

Every ggplot2 chart can be read as a set of choices: which data to draw, which variables control the marks, and which layers appear. Naming those pieces makes unfamiliar plots easier to understand. Start with a small scatter plot, then learn how to store it, add components, and interpret R's feedback. The same working pattern will support more complex plots as you add new geoms, calculations, and display controls.

1.1 The pieces of a ggplot2 plot

A plot is built from choices you can change separately. The grammar of graphics gives those choices names, so you can read a chart, explain how it works, and adapt it without starting again. Leland Wilkinson described the grammar in 1999; Hadley Wickham developed the layered grammar behind ggplot2 in 2010.

Start with data, mappings, and a geom

Load the packages and build a scatter plot:

library(ggplot2)
library(palmerpenguins)

ggplot(penguins, aes(x = flipper_length_mm, y = body_mass_g)) +
  geom_point(aes(color = species))

The data are a table. Each row describes one penguin; each column describes a variable. The palmerpenguins table has 344 rows and eight columns: species, island, bill_length_mm, bill_depth_mm, flipper_length_mm, body_mass_g, sex, and year. Its species counts are 152 Adelie, 68 Chinstrap, and 124 Gentoo. Its island counts are 168 Biscoe, 124 Dream, and 52 Torgersen.

An aesthetic mapping connects a column to a visual property. Here flipper length sets horizontal position, body mass sets vertical position, and species sets color. A geom supplies the marks: geom_point() draws points. The call to ggplot() establishes the plot; adding the geom makes the observations visible.

Use the palmerpenguins columns shown above. Base R 4.5 also supplies a penguin data set, but its names include flipper_len and body_mass. Explicitly using palmerpenguins::penguins selects the table used in these examples. library(tidyverse) also loads ggplot2.

Read the parts that use defaults

A point layer uses the identity stat: it draws the measured values without summarizing them. Its identity position adjustment leaves each point at its mapped position. Continuous scales turn the two measurements into axis positions; a discrete color scale assigns a color to each species and creates a legend.

Cartesian coordinates place the axes at right angles. There are no facets, so all observations share one panel. The default gray theme supplies the background, grid, and text styling. The cloud slopes upward: longer flippers tend to accompany greater body mass, with a correlation of about 0.87. Gentoo penguins occupy the larger-bodied cluster.

A layer combines data, mappings, geom, stat, and position adjustment. Multiple layers can draw different views of the same observations. The plot’s scales, coordinates, facets, and theme apply across its layers.

ComponentQuestion it answers
StatWhat values must be computed?
Position adjustmentHow should overlapping marks be arranged?
ScaleHow do values become positions, colors, or sizes?
CoordinatesHow are positions placed on the page?
FacetsWhich subsets get separate panels?
ThemeHow should the non-data parts look?
Change a component

Adding geom_smooth() adds a summary of the relationship. Replacing geom_point() with it shows the trend without individual points. A single vertical stacked bar can become a pie chart by adding coord_polar(theta = "y"); the data and bar layer can stay the same.

Mappings need variables in columns. If measurements for separate years sit in separate columns, there is no single year column to map to color. Reshape that table into long form, for example with tidyr::pivot_longer(), before building that mapping.

Key Takeaways

  • A layer combines data, mappings, a geom, a stat, and a position adjustment.
  • Scales, coordinates, facets, and theme describe the plot across its layers.
  • A mapping links a variable to a visual property; a geom supplies the marks.
  • Use one column per variable so each mapping has a column to refer to.

1.2 Write and repair a plot call

Build a plot in small, runnable steps. That makes syntax errors easier to locate and lets you check what each new layer changes. The package is named ggplot2, while its main function is ggplot().

Join components with plus
library(ggplot2)
library(palmerpenguins)

p <- ggplot(penguins, aes(flipper_length_mm, body_mass_g)) +
  geom_point()
p

The first argument of ggplot() is the data and the second is the mapping. Inside aes(), the first two unnamed arguments mean x and y. Writing aes(x = flipper_length_mm, y = body_mass_g) gives the same mapping and makes those roles explicit.

ggplot() by itself gives an empty panel. A mapping adds axes, but a geom is needed to draw the data. Keep + at the end of a line, where it tells R that the expression continues. If the previous line is already complete, a new line beginning with + geom_point() is a separate expression and fails.

A pipe can pass a table into ggplot(). From that point onward, join plot components with +:

penguins |>
  ggplot(aes(x = species)) +
  geom_bar()

A pipe between the plot and its geom does not add a layer. Check the operator first when an error suggests that a pipe was used in place of plus.

Store a plot and control drawing order

Assignment creates the object p without drawing it. Typing p displays it at the interactive console. Use print(p) inside a function, a loop, or a script run through source().

p_with_trend <- p + geom_smooth(method = "lm")
print(p_with_trend)

This creates a second plot; p still contains only points. If you want to update the stored plot itself, assign the result back to p.

Layers draw in the order you add them. A smoother added after points sits above them. A reference line or shaded region intended as a background belongs before the points, so it does not cover them.

Interpret R’s feedback
FeedbackWhat happenedWhat to do
MessageThe plot ran and reports a choice, such as histogram bins.Decide whether to specify the choice yourself.
WarningThe plot ran, but rows were dropped or a feature needs attention.Read the reason and check the affected data or code.
ErrorThe requested plot failed.Fix the named problem before continuing.

The flipper-length versus body-mass plot has two rows without measurements. Its missing-row warning is expected because those observations cannot be placed. After checking the count, geom_point(na.rm = TRUE) suppresses that warning; it does not recover the missing measurements.

Find the smallest failing change

If R reports an unknown column, compare the spelling with names(penguins). Names are case-sensitive: Species and species differ. If it cannot find ggplot(), load ggplot2. Installing a package and loading it are separate actions.

An unmatched parenthesis or quote leaves the console waiting at a continuation prompt. Press Escape, fix the incomplete expression, and rerun it. That console prompt is different from the plus operator joining plot components.

Return to the last call that worked, then restore one argument or layer at a time. Use ?geom_point to inspect its examples and its supported aesthetics; required aesthetics are marked in the help page. This isolates the change that caused the failure.

Key Takeaways

  • Keep + at the end of a line when a plot continues.
  • Use a pipe into ggplot() and + between plot components.
  • Assigning stores a plot; print() displays it reliably in loops and functions.
  • Later layers draw over earlier layers.
  • Investigate warnings before suppressing expected missing-row warnings.
2

Map variables to aesthetics and choose geoms

Variables become visible through position, color, shape, and other aesthetics. Decide which properties should vary and which should stay fixed, then choose geoms that reveal a distribution or relationship. Grouping and layer inheritance affect what is drawn and what is fitted. Dense plots also need ways to reveal observations that overlap, while extra variables can expose patterns hidden by a pooled view.

2.1 Choose what varies and what stays fixed

An aesthetic is a visual property of a mark. Position, color, fill, shape, size, line type, and opacity can communicate data. The first decision is whether the property should vary with a column or stay the same across the layer.

Map a variable or set a constant
GoalCode inside a point layerResult
Color by speciesaes(color = species)Species get colors and a legend.
Make every point bluecolor = "blue"One fixed color, with no color legend.

Inside aes(), even a quoted string is mapped. aes(color = "blue") creates one category named "blue"; the default palette chooses its color. It does not request blue paint. Move a fixed value outside aes().

ggplot(penguins, aes(flipper_length_mm, body_mass_g)) +
  geom_point(aes(color = species), size = 3, alpha = 0.5)

Species varies, while point size and opacity stay fixed. alpha runs from 0, invisible, to 1, solid.

Match the property to the geom

color controls points, lines, and outlines. fill controls interiors of bars, boxes, areas, and density curves. Shapes 21–25 have both: geom_point(shape = 21, color = "black", fill = "gold") draws a gold interior with a black outline.

Use linewidth for line thickness and outlines of bars, boxes, and areas. Use size for points and text, and stroke for the thickness of a point’s outline. Check the geom’s help page when an aesthetic has no effect; each geom supports its own set.

Respect the variable type

A character or factor column produces a discrete scale with separate keys. A numeric column produces a continuous scale, such as a color gradient. Years stored as numbers are numeric even when the intended comparison is between three annual groups. aes(color = factor(year)) requests separate categories.

Shape needs discrete categories. A continuous shape mapping fails, and the default shape palette supports only six categories. Mapping seven vehicle classes from mpg to shape leaves the seventh without a drawable shape. Discrete size or opacity mappings also invite misleading comparisons because larger or darker marks suggest more.

Place mappings where they belong

Global mappings are inherited by layers. A local mapping adds to them or replaces the same aesthetic for that layer.

ggplot(penguins, aes(flipper_length_mm, body_mass_g)) +
  geom_point(aes(color = species)) +
  geom_smooth(method = "lm")

Only the points map color, so the smoother fits one overall line. Move color = species into the global aes() and the smoother also inherits it: now it fits one line per species. This changes the analysis, not just the palette.

Discrete mapped aesthetics normally define groups for lines, boxplots, and smoothers. aes(group = species) requests species groups without assigning them different colors. group = 1 explicitly requests one group. For several time series, map the series identifier to group or a discrete color so lines do not connect unrelated series.

Mapping species to both color and shape gives two ways to recognize the same groups. Set both legend titles to "Species" so they can merge into one guide. This helps readers distinguish groups when colors are hard to tell apart.

Key Takeaways

  • Put variable mappings inside aes() and fixed settings outside it.
  • Use fill for interiors and color for points, lines, and outlines.
  • Use linewidth for lines, size for points and text, and stroke for point outlines.
  • Global discrete mappings can change how statistical layers group the data.
  • Map a numeric category through factor() when separate groups are intended.
  • Color and shape can identify the same groups together.

2.2 Read categories and numeric distributions

A distribution describes the values a variable takes and how often they occur. A category count and a binned numeric measurement need different computations, even though both can be drawn with bars.

Count categories
ggplot(penguins, aes(x = species)) +
  geom_bar()

geom_bar() counts rows. No y mapping is needed: the bars have heights 152, 68, and 124 for Adelie, Chinstrap, and Gentoo. For long category names, aes(y = species) draws horizontal bars.

Character values appear alphabetically. To show the most common species first, use aes(x = forcats::fct_infreq(species)). The order becomes Adelie, Gentoo, Chinstrap. A factor carries its level order, so ordering belongs to the values supplied to the axis.

Bin numeric values
ggplot(penguins, aes(x = body_mass_g)) +
  geom_histogram(binwidth = 200)

A histogram groups nearby measurements into intervals called bins. Each bar counts observations in one interval. Here the bar width is 200 g, and the measured masses span 2,700–6,300 g. That 3,600 g span gives roughly 18 intervals; exact edge placement affects how many bars are drawn.

Without binwidth or bins, ggplot2 uses 30 bins and reports that choice. Treat the result as a starting view. Very narrow 20 g bins make this histogram spiky; 2,000 g bins hide much of its shape. Compare several reasonable widths to see which features remain.

boundary sets a bin edge and center sets a bin center. Those choices matter for rounded measurements. With the default right-closed bins, a value exactly on a shared boundary enters the bin to its left. Changing width without checking alignment can make a cluster seem to appear or vanish.

DisplayInput to the counting stepMeaning of adjacent bars
Bar chartSeparate categoriesDifferent named groups
HistogramNumeric intervalsNeighboring ranges on one continuous axis

Histogram bars touch because the ranges meet. geom_histogram() rejects categorical x values. geom_bar() on numeric x counts each distinct value separately, so it does not provide the binning a histogram needs.

Compare shapes

geom_density() draws a smooth distribution curve whose total area is 1. Its height is density, not a count or the probability of one exact value. adjust = 0.5 follows local bumps more closely; adjust = 2 smooths them more strongly.

geom_freqpoly(binwidth = 200) joins histogram counts with a line. Several frequency polygons can share a panel without filled bars covering each other. Use the same bin width when comparing their shapes.

Look for the center, spread, peaks, skewness, gaps, and unusual values. A mass histogram with fill = species reveals that the heavier cluster, roughly 4,700–5,500 g, is mostly Gentoo. The grouping helps explain a feature of the overall distribution.

When a few categories are much more common than the rest, short bars can be hard to see. coord_cartesian(ylim = c(0, 5)) enlarges the lower part of the display while retaining the counts. It crops tall bars, so read that view as a close look at rare categories.

Key Takeaways

  • Use geom_bar() to count categories and geom_histogram() to bin numeric measurements.
  • Try different histogram widths and check where the bin edges fall.
  • A density curve has total area 1; its height is not a count.
  • Frequency polygons make overlapping binned distributions easier to compare.

2.3 Show relationships without hiding observations

The types of your variables help determine what a geom must show. A plot of two measurements places observations in a numeric plane. A comparison of measurements across categories needs a separate distribution for each group.

Match geoms to the variables
VariablesUseful geomsWhat you can compare
Two numericgeom_point(), with an optional smootherDirection, shape, and spread of a relationship
Numeric and categoricalgeom_boxplot(), geom_violin(), grouped density curvesGroup centers, spreads, or distribution shapes
Two categoricalStacked or filled bars, geom_count()Counts or shares of combinations
Numeric over ordered timegeom_line()Change through time

ggplot(penguins, aes(species, body_mass_g)) + geom_boxplot() shows a median mass of 5,000 g for Gentoo and 3,700 g for each of the other species. Violins reveal distribution shape; overlaid density curves can compare it in one panel. For filled densities, use transparency so one curve does not hide another.

An island bar filled by species shows both totals and composition. Biscoe has 44 Adelie and 124 Gentoo penguins, totaling 168. Dream has 56 Adelie and 68 Chinstrap, totaling 124. All 52 Torgersen penguins are Adelie. With position = "fill", the bars show within-island shares: Gentoo account for about 74% on Biscoe. Equal-height bars no longer show the island sample sizes.

Combine layers and preserve groups

A scatter plot of flipper length and body mass shows a strong upward relationship. Add geom_smooth(method = "lm") to draw a straight fitted trend. Several geoms can inherit the same axes, while a layer can use its own smaller table to highlight selected observations.

For a time series, x order matters:

tibble::tibble(
  month = 1:6,
  temp_c = c(3, 5, 9, 13, 17, 20)
) |>
  ggplot(aes(month, temp_c)) +
  geom_line() +
  geom_point()

geom_line() joins points in x order. geom_path() joins them in row order, which suits a path through locations. With several series, map their identifier to group or a discrete color; otherwise one line can zigzag between series.

Reveal crowded observations

Overplotting occurs when marks cover one another. A dense region can look like one solid patch even when it contains many observations. Smaller points and alpha = 0.1 help reveal concentration. Jitter separates points with repeated or rounded coordinates.

For a large table such as the 53,940-row diamonds data, geom_bin_2d() counts observations in rectangular cells. geom_hex() uses hexagonal cells and needs the hexbin package. Fill then represents counts, replacing thousands of overlapping points with a summary of local concentration.

To compare distributions along a numeric axis, make explicit groups. cut_width(carat, 0.1) groups diamonds into 0.1-carat intervals; cut_number(carat, 5) makes five groups with about equal numbers of rows. These support grouped boxplots with different grouping aims.

Check what an extra variable reveals

Color can expose a pattern hidden by pooling. Bill length and bill depth have an overall correlation of about −0.24, but the within-species correlations are positive: about 0.39 for Adelie and 0.65 for Chinstrap and Gentoo. Separate species clusters create a different overall pattern. Faceting by island while coloring by species can reduce overlap when too many encodings crowd one panel. An association describes a pattern; explaining its cause needs further evidence.

Key Takeaways

  • Choose geoms from both the question and the variable types.
  • Counts and within-group shares answer different questions.
  • geom_line() follows x order; geom_path() follows row order.
  • Use grouping to keep separate series from being connected.
  • Transparency, jitter, and two-dimensional bins address different kinds of crowding.
  • A pooled relationship can differ from relationships within groups.
3

Use statistical transformations and position adjustments

A bar, a box, and a smooth line often show values calculated from many rows. Knowing the calculation behind a layer helps you choose the right inputs and read its result correctly. Work from raw rows to counts and proportions, then examine quartiles, group summaries, and fitted trends. Position adjustments give those results different arrangements, changing whether totals, shares, or separate groups are easiest to compare.

3.1 Understand the values a layer computes

A geom determines the marks you see. A statistical transformation, or stat, determines the values those marks represent. Every layer has both, even when the code names only one.

Identify the default computation
GeomDefault statValues drawn
Point, line, columnIdentitySupplied values
BarCountNumber of rows at each category
Histogram, frequency polygonBinCounts within numeric intervals
DensityDensityA smoothed distribution
BoxplotBoxplotQuartiles, whiskers, and outliers
SmoothSmoothA fitted trend and its uncertainty

An identity stat leaves values unchanged. A counting stat turns many raw rows into a smaller table of counts. For aes(x = species), geom_bar() computes three rows with counts 152, 68, and 124, then draws three bars.

Use the right layer for existing heights

If your table already contains the bar heights, draw those heights:

counts <- tibble::tibble(
  species = c("Adelie", "Chinstrap", "Gentoo"),
  n = c(152, 68, 124)
)
ggplot(counts, aes(species, n)) +
  geom_col()

geom_col() uses identity. geom_bar(stat = "identity") gives the same result. The ordinary geom_bar() counts rows, so adding both x and y to that default layer causes an error: stat_count() accepts only one of x and y. Choose whether the layer must count observations or display an existing height before fixing its syntax.

Map computed variables

A stat can create variables that were absent from the input table. after_stat() tells the mapping to use those computed values.

ggplot(penguins, aes(
  x = species,
  y = after_stat(prop),
  group = 1
)) +
  geom_bar()

stat_count() produces count and prop. With one group, the denominator spans all species: the shares are about 0.442, 0.198, and 0.360. Without group = 1, discrete x creates a separate group for each species. Each category then constitutes its whole group and its computed proportion is 1.

The grouping rule belongs to the calculation. Changing the y-axis text to percentages formats results; it cannot repair a denominator computed for the wrong group.

Put a histogram and density on the same scale
ggplot(penguins, aes(body_mass_g)) +
  geom_histogram(
    aes(y = after_stat(density)),
    binwidth = 200,
    fill = "gray85"
  ) +
  geom_density()

The histogram now has total bar area 1, matching the density curve. A default count histogram and a density curve use different vertical quantities and should not be read as sharing the same scale. stat_bin() also exposes count, ncount, ndensity, and width; its help page lists the computed variables.

Statistics run separately for each group in each panel. A histogram filled by species counts bins within species, while faceting by island separates the computation by island.

You can name a stat directly: stat_count() draws bars by default, just like geom_bar(). stat_summary() defaults to a point with a range through it.

Key Takeaways

  • Every layer pairs a geom with a stat.
  • Use geom_bar() for raw rows and geom_col() for supplied heights.
  • after_stat() maps variables created by the layer computation.
  • Computed proportions depend on grouping.
  • Stats are calculated separately within groups and facet panels.

3.2 Interpret boxes, summaries, and trend bands

A summary layer replaces individual observations with a compact description. Read what it computes before interpreting its marks: a box, a mean with a range, and a fitted line each answer a different question.

Work through a boxplot

The box runs from the first quartile, Q1, to the third quartile, Q3. It spans the middle half of the distribution. The line inside marks the median. The interquartile range is:

IQR=Q3−Q1

For the 68 Chinstrap masses, Q1 is 3,487.5 g, the median is 3,700 g, and Q3 is 3,950 g. Subtraction gives an IQR of 462.5 g. Multiplying by 1.5 gives 693.75 g, so the lower fence is 2,793.75 g and the upper fence is 4,643.75 g.

A whisker ends at an observed value inside its fence. The extreme eligible masses are 2,900 g and 4,550 g, so those are the whisker endpoints. The observations at 2,700 g and 4,800 g lie beyond the fences and appear as separate outlier points. The fences themselves are not the whisker endpoints. An outlier under this rule can still be a valid measurement.

A box does not reveal every gap or peak. Add individual points to expose that detail:

ggplot(penguins, aes(species, body_mass_g)) +
  geom_boxplot(outliers = FALSE) +
  geom_jitter(width = 0.2, height = 0, alpha = 0.4)

Suppressing the boxplot’s outlier marks avoids drawing those observations twice; the point layer supplies them. outliers = FALSE also discards those values from that layer’s scale training. Without a raw-point layer, outlier.shape = NA hides the marks while retaining the full range. geom_violin() exposes distribution shape, and varwidth = TRUE makes box widths proportional to the square root of group sizes.

Choose a summary deliberately

stat_summary() summarizes y for each x. Its default uses mean_se(): a point at the mean with a range one standard error below and above it. The penguin mean masses are about 3,701, 3,733, and 5,076 g by species.

stat_summary(fun = median, fun.min = min, fun.max = max)

This requests a median point with the full observed range. stat_summary(fun = mean, geom = "col") makes mean-height columns. fun.data = mean_cl_normal, which needs Hmisc, supplies 95% confidence intervals for means. In older code, fun.y names the argument now called fun.

Read a smoother’s model and band

geom_smooth() fits y against x. With no method specified, it uses loess when the largest group has fewer than 1,000 observations and a generalized additive model otherwise. For 342 measured penguins the default is loess. A smaller loess span follows local changes more closely; the default is 0.75.

method = "lm" fits a straight line. Adding formula = y ~ poly(x, 2) allows curvature with a squared term. The default band is a 95% confidence interval for the mean trend, not a range expected to contain 95% of individual observations. se = FALSE removes it.

Discrete color mappings fit separate models, each over its group’s x range. fullrange = TRUE extends the drawn fit. Sparse ends of a trend have less support, and a straight-line fit can miss a clearly curved relationship.

Key Takeaways

  • A box spans Q1 to Q3 and its interior line marks the median.
  • Whiskers end at observed values within the 1.5-IQR fences.
  • A separate outlier point need not be an error.
  • Choose the function and range when drawing a group summary.
  • A smoother band describes uncertainty about the mean trend.
  • Discrete grouping determines how many separate smoothers are fitted.

3.3 Arrange marks that share a position

A position adjustment controls how a layer arranges marks that would overlap. It can reveal totals, shares, group comparisons, or repeated observations. It does not select the geom’s statistical calculation.

Compare bar arrangements

Start with the island-by-species mapping:

ggplot(penguins, aes(island, fill = species)) +
  geom_bar()

Bars stack by default. Biscoe’s 44 Adelie and 124 Gentoo observations form a total height of 168. The total is easy to compare with other islands, but only the bottom segment has a common zero baseline.

PositionWhat the bar heights showMain comparison
"stack"Counts added within each xTotals and composition
"fill"Each stack rescaled to height 1Within-x shares
"dodge"Counts placed side by sideIndividual groups from zero
"identity"Counts at the same x, overlappingRequires care because bars can hide bars

geom_bar(position = "fill") makes Biscoe about 26% Adelie and 74% Gentoo. Dream is about 45% Adelie and 55% Chinstrap; Torgersen is 100% Adelie. Relabel the vertical axis "Proportion" because the default count label no longer describes the display. A percentage label function can make the scale easier to read.

geom_bar(position = "dodge") places species beside one another within each island. Each starts at zero. If combinations are missing, default dodging lets the remaining bars widen. On Torgersen only Adelie occurs, so its bar fills the slot. position_dodge(preserve = "single") keeps an individual bar’s width fixed. position_dodge2() also handles varying widths and is the default for boxplots.

With identity positioning, bars sit in front of each other. alpha = 0.3 or fill = NA can reveal some overlap, but a hidden bar is difficult to compare accurately. Identity is the ordinary choice for points and lines, whose mapped positions should remain intact.

Separate repeated points

Jitter adds small random offsets. For species on x and mass on y, spread points sideways while keeping measured mass exact:

ggplot(penguins, aes(species, body_mass_g)) +
  geom_point(position = position_jitter(
    width = 0.2, height = 0, seed = 7
  ))

width and height set jitter in data units. Here horizontal noise separates points within a category, while height = 0 prevents invented changes in mass. geom_jitter() is a point geom with jitter positioning; its default vertical jitter is why setting height explicitly matters. A seed makes the offsets reproducible across repeated runs.

Move text by a known amount

Nudging adds a fixed offset, with no randomness. geom_text(aes(label = species), nudge_y = 100) places each label 100 g above its anchor. Choose nudging when the same direction and distance should apply to every label. Choose jitter when repeated marks need separation without a meaningful fixed direction.

Key Takeaways

  • Stack shows totals; fill shows shares within each stack.
  • Dodge gives separate bars a common zero baseline.
  • preserve = "single" keeps individual dodged bar widths consistent.
  • Set jitter to zero along an axis whose exact values must be retained.
  • Nudge is a fixed shift, while jitter is random.
4

Control facets, scales and coordinate systems

Once the layers work, control the space in which they are drawn. Facets separate subsets, scales translate values into positions and colors, and coordinates determine the displayed view. These choices can look similar while affecting the calculation differently. Learn when a change only alters the view, when it changes the data used by a stat, and how axes and legends make those decisions readable.

4.1 Give groups their own panels

Facets repeat the same plotting instructions for subsets of a table. Each panel shows one subset, making it easier to see groups that overlap in a single plot. The default shared scales also let you compare their positions directly.

Wrap panels or align a grid
ggplot(penguins, aes(flipper_length_mm, body_mass_g)) +
  geom_point(aes(color = species)) +
  facet_wrap(~ island, nrow = 1)

facet_wrap() makes a panel for each island and wraps panels into a layout. nrow and ncol control its shape. facet_wrap(vars(island)) expresses the same choice with vars() notation. Wrap is useful for one variable, or for combinations that need no strict row-by-column alignment.

facet_grid(sex ~ species) assigns sex to rows and species to columns. The equivalent form is facet_grid(rows = vars(sex), cols = vars(species)). A dot means no variable in that direction: facet_grid(. ~ species) uses columns only.

Missing faceting values can create a panel too. Penguin sex is missing for 11 observations. The sex-by-species grid has female, male, and NA rows across three species columns, making nine panels. The NA row contains six Adelie and five Gentoo observations; its Chinstrap cell is empty. If the missing-sex row is unwanted, remove those rows from the plotting data deliberately.

Decide which ranges should be shared
Scale settingWhat can vary
"fixed"Neither axis range
"free_x"Horizontal ranges
"free_y"Vertical ranges
"free"Both ranges

Fixed scales make the same position mean the same value in every panel. Free scales expand each subset to show more of its local shape, but equal-looking heights can represent different values.

In facet_wrap(), free ranges can vary by panel. In facet_grid(), alignment imposes an extra rule: every panel in a column shares x, and every panel in a row shares y. Thus scales = "free_y" frees y between rows, not separately inside each row. space = "free" can make panel dimensions proportional to their ranges, but only along an axis whose scale is also free.

Make strips and subsets readable

Panel strips normally show just values such as "Adelie". labeller = label_both includes the variable name, producing "species: Adelie". In facet_wrap(), strip.position = "bottom" moves the strips below the panels.

Faceting directly by a continuous column can create a panel for every distinct value. Form useful ranges first. facet_wrap(~ cut_number(bill_depth_mm, 3)) makes roughly equal-count groups, plus an NA panel for the two missing measurements. cut_width() instead forms fixed-width intervals.

Choose between color and facets

A few distinct groups can be easier to compare together using color. Many overlapping groups often need separate panels. Combining the two is useful when they have separate jobs: color identifies species, while panels separate islands.

Statistics are computed inside each panel. A smoother in each species facet is fitted to that species, and a bar chart in each island facet counts only that island’s rows. Adding facets can therefore change the displayed summary, even when the layer code is unchanged.

Key Takeaways

  • facet_wrap() wraps subsets into panels; facet_grid() aligns row and column variables.
  • Shared scales support direct comparisons of position across panels.
  • Grid scales remain shared within each column for x and within each row for y.
  • Missing faceting values can form their own panel.
  • Stats are computed separately within panels.

4.2 Control axis values, spacing, and text

A scale translates data values into visual values. Its guide, an axis or legend, lets readers translate back. ggplot2 chooses default scales, but you can replace them to control titles, tick positions, labels, ranges, and padding.

Separate tick positions from their labels
scale_x_continuous(
  name = "Flipper length (mm)",
  breaks = seq(170, 230, by = 10)
)

This gives seven ticks from 170 to 230 mm. breaks chooses values; labels chooses what those values look like. labels = NULL hides tick text while keeping ticks. breaks = NULL removes ticks, their labels, and their grid lines.

The scales package supplies formatting functions. scales::label_comma() displays 1234567 as "1,234,567". scales::label_percent() displays 0.25 as "25%"; the multiplication by 100 is part of formatting. scales::label_number(suffix = " g") adds a unit. Use the function in the scale, such as scale_y_continuous(labels = scales::label_percent()).

Transform spacing without hiding the original values

scale_x_log10() gives equal distances to equal ratios. Values 2, 20, 200, and 2,000 are equally spaced, while the labels remain on the original scale. scale_x_continuous(transform = "log10") is equivalent. Older code calls this argument trans.

An ordinary log scale needs strictly positive values. Negative values become NaN and are dropped. Zero becomes -Inf: point layers can draw it at the panel edge, while stats leave it out. Inspect nonpositive values before applying the transformation.

Mapping aes(x = log10(price)) also transforms positions, but the labels now show logged values such as 2, 3, and 4. A log scale retains labels such as 100, 1,000, and 10,000. In both cases, a stat such as a smoother receives transformed values. Other choices include scale_x_sqrt() and scale_x_reverse().

Control category order and dates

A character axis uses alphabetical order; a factor axis uses level order. scale_x_discrete(limits = c("Gentoo", "Adelie", "Chinstrap")) supplies an explicit order, dropping any omitted categories. labels = c(Adelie = "Adélie") changes the printed name without altering the data. guide = guide_axis(n.dodge = 2) arranges crowded labels in two rows.

For a Date column, scale_x_date(date_breaks = "1 month", date_labels = "%b %Y") labels monthly ticks like "Jan 2026". %d means day, %m numeric month, %b abbreviated month name, and %Y four-digit year. Month names follow the language of the R session.

Distinguish display adjustments from data removal

Continuous scales add 5% padding at each end by default. To seat bars on the axis while leaving room above, use expand = expansion(mult = c(0, 0.05)) in the y scale.

Continuous scale limits turn values outside their range into missing values before stats are computed. xlim(), ylim(), and lims() have that effect too. To keep all observations in a smoother while showing a narrower view, use coord_cartesian(xlim = c(190, 220)).

A secondary axis converts the same primary values into another unit. sec_axis(~ . / 1000, name = "Body mass (kg)") on the gram axis displays kilograms. It does not provide a separate axis for an unrelated data series.

Key Takeaways

  • Breaks set tick positions; labels format the values shown there.
  • Log scales show equal ratios at equal distances and require positive data.
  • Scale transformations occur before statistical computations.
  • Scale limits can remove values; coordinate limits provide a viewing window.
  • A secondary axis converts the primary values into another representation.
  • Date label codes format a Date axis without changing the underlying dates.

4.3 Make colors and legends mean the right thing

A color scale assigns colors to mapped values, while its legend explains that assignment. Choose the scale for both the variable type and the aesthetic that actually paints the marks.

Match the scale to the data
Values being shownExample scaleMeaning
Unordered categoriesscale_color_brewer(palette = "Set2")A distinct color for each group
A continuous measurementscale_color_viridis_c()A continuous progression
Discrete categories with viridisscale_color_viridis_d()Separate sampled colors
Binned measurementsscale_color_viridis_b()Color steps for numeric ranges

Default discrete colors use separated hues, and the default continuous gradient runs from dark to light blue. Theme settings can also control default palettes in ggplot2 4.0.

ColorBrewer supplies qualitative palettes for categories, sequential palettes such as "Blues", and diverging palettes such as "RdBu". scale_fill_distiller() applies Brewer colors continuously; scale_fill_fermenter() applies them in bins. Qualitative palettes have finite capacity: Set2 provides eight colors. RColorBrewer::display.brewer.all() displays the choices.

Viridis palettes change evenly in lightness and remain useful in grayscale and for common color-vision deficiencies. Another discrete option is the eight-color ggthemes::scale_color_colorblind().

Assign colors by name
scale_color_manual(values = c(
  Adelie = "darkorange",
  Chinstrap = "purple",
  Gentoo = "cyan4"
))

Names tie colors to categories, so changing category order does not swap their meanings. An unnamed vector follows level order. Too few colors for the categories causes an error.

For continuous fill, scale_fill_gradient(low = "white", high = "darkblue") sets two endpoints. scale_fill_gradient2(low = "blue", mid = "white", high = "red", midpoint = 0) shows departures on either side of zero. scale_fill_gradientn(colors = ...) supports several color stops.

The aesthetic must match. Bars mapped with fill = species need a fill scale; a color scale changes their outlines only when color is mapped. A scale can target both with aesthetics = c("color", "fill").

Keep the key readable

Move a legend with theme(legend.position = "bottom"), or choose "top", "left", "right", or "none". For placement inside the panel, use legend.position = "inside" and legend.position.inside = c(0.9, 0.2). The pair gives fractions of panel width and height.

guides(color = guide_legend(
  nrow = 1,
  override.aes = list(size = 4, alpha = 1)
))

This makes the legend keys larger and opaque without changing small, transparent plotted points. show.legend = FALSE excludes one layer from a guide.

Color and shape mapped to the same variable can share one legend when titles and categories match. Set labs(color = "Species", shape = "Species"); changing only one title can split the guide. Shape, size, and line type have their own scales too. scale_shape_manual(values = c(16, 17, 15)) sets shapes, while scale_size_area(max_size = 6) makes point area proportional to value and maps zero to zero area.

Key Takeaways

  • Match discrete, continuous, and binned color scales to the variable.
  • Named manual colors stay attached to categories when order changes.
  • Match a scale to the mapped aesthetic: fill and color have different jobs.
  • A legend override changes keys without changing plotted marks.
  • Legends merge when their mapped categories and titles match.

4.4 Zoom without changing the fitted result

Coordinates turn mapped x and y positions into places on the page. The default, coord_cartesian(), draws perpendicular axes. Coordinate operations happen after the statistical calculations, which makes them useful for changing the view while retaining those calculations.

Compare two identical-looking windows

Start with penguin flipper length against body mass and a smoother. The full scatter has 342 measured observations and two rows without measurements.

Range instructionData used by the smootherVisible x window
scale_x_continuous(limits = c(190, 220))Only the 230 measured rows in range190–220 mm
coord_cartesian(xlim = c(190, 220))All 342 measured rows190–220 mm

Scale limits remove 112 measured rows outside the interval, in addition to the two missing rows. The smoother is refitted to the smaller subset. Coordinate limits crop the view of the original fit. Filtering the data first also changes the sample deliberately; it is useful when the subset itself is the intended analysis.

ggplot(penguins, aes(flipper_length_mm, body_mass_g)) +
  geom_point() +
  geom_smooth(method = "lm") +
  coord_cartesian(xlim = c(190, 220))

A narrowed view can be especially consequential for bars. Their lengths are read from zero. A scale range of 50–200 removes a bar’s zero baseline, so the species bars disappear. Coordinate zoom crops them instead, but their visible lengths can exaggerate differences. Keep the zero baseline for a bar-length comparison.

Choose orientation and aspect ratio

coord_flip() swaps the displayed axes. For most current geoms, swapping the mappings is simpler: aes(x = body_mass_g, y = species) gives horizontal boxplots.

coord_fixed(ratio = 1) makes one unit on x and one unit on y equally long. coord_cartesian(ratio = 1) offers the same control in ggplot2 4.0. Equal physical units are useful when comparing bill length and depth, both in millimeters. coord_quickmap() supplies an approximate aspect ratio for longitude and latitude.

Know when transformations change the calculation

scale_x_log10() transforms x before fitting a smoother. With method = "lm", the fitted relationship is linear in logged x and appears straight on that axis.

coord_transform(x = "log10") transforms after the fit. The model uses original x values, then the coordinate transformation bends its displayed line. Older code calls this function coord_trans(). The position of a transformation in the plotting process can therefore change the model represented by the display.

Use polar coordinates and clipping
ggplot(penguins, aes(x = "", fill = species)) +
  geom_bar(width = 1) +
  coord_polar(theta = "y")

One vertical stacked bar becomes a pie: y becomes angle. With theta = "x", bars can become a rose chart. coord_radial() provides newer polar options, including an inner radius. Bars usually support more precise share comparisons because lengths are easier to compare than angles or areas.

coord_cartesian(expand = FALSE) removes padding. clip = "off" allows elements such as annotations to extend beyond the panel boundary; place them carefully so they do not cover axis labels.

Key Takeaways

  • Coordinate zoom keeps the data used by stats; scale limits can change that data.
  • Keep zero visible when comparing bar lengths.
  • A fixed coordinate ratio controls the physical length of axis units.
  • A scale transformation precedes stats; a coordinate transformation follows them.
  • coord_polar(theta = "y") converts a single stacked bar into a pie.
5

Communicate with labels, annotations, themes and saved figures

A finished figure needs enough context to stand on its own. Labels explain the variables and finding, annotations point to useful details, and themes organize the surrounding text and lines. The final export size determines how all of that reads. Build a reusable style, save a specific plot with recorded dimensions, and combine different plots when a single panel cannot show the complete comparison.

5.1 Write labels that explain the finding

A plot made during exploration helps you discover a pattern. A plot shared with other people needs enough text for them to understand that pattern without reading your code. labs() controls titles, axis titles, legend titles, captions, and alternative text.

Give each label a job

A title states the finding, such as "Gentoo penguins are the heaviest of the three species". A subtitle explains the sample or setting: "Body mass of 342 penguins measured in 2007–2009". A caption identifies the source. Axis titles name the measured variable and its unit.

p <- ggplot(penguins, aes(flipper_length_mm, body_mass_g)) +
  geom_point(aes(color = species, shape = species)) +
  labs(
    title = "Longer flippers accompany greater body mass",
    subtitle = "Penguins measured in 2007–2009",
    x = "Flipper length (mm)",
    y = "Body mass (g)",
    color = "Species",
    shape = "Species",
    caption = "Data: palmerpenguins R package"
  )

The x and y mappings still use the original column names. Labels change what readers see, not the data or calculations. Without explicit labels, ggplot2 normally displays column names such as body_mass_g, which leave units buried in programming notation.

Name legends by aesthetic

labs(color = "Species") titles the color guide. Use fill, shape, or size to title those guides. A variable’s column name is not the argument name: labs(species = "Species") does not title a color legend.

When color and shape encode species together, give both the same title. With matching categories, the two guides can merge. If only color is renamed, the different titles can produce separate legends.

Use NULL to remove a label: labs(x = NULL) removes the x-axis title while leaving its values visible. The tag argument adds a short panel identifier, useful when a figure is discussed as panel A or B.

Control line breaks and mathematical labels

A long title can include an explicit line break:

labs(title = "Gentoo penguins are the heaviest\nof the three species")

The \n belongs inside the quoted R string. By default a title aligns with the plot panel. theme(plot.title.position = "plot") aligns it with the whole plot’s left edge, which can help when y-axis tick labels are wide.

R expressions can format mathematical notation. labs(y = quote(Area ~ (m^2))) displays "Area (m²)". The tilde inserts spacing and the caret makes a superscript. quote(x[i]) creates a subscript; ?plotmath lists available notation.

Describe the plot in words

Alternative text should identify the chart, its variables, and its main pattern:

p <- p + labs(
  alt = paste(
    "Scatter plot of penguin body mass against flipper length.",
    "Mass tends to rise with flipper length; Gentoo occupy",
    "the larger-bodied cluster."
  )
)
get_alt_text(p)

labs(alt = ...) stores the description, and get_alt_text() retrieves it. A publishing or display tool must carry that text into the image’s alternative-text field. A description that only says "a scatter plot" leaves out the information a reader needs from the figure.

Key Takeaways

  • Use a title for the finding, a subtitle for context, and a caption for the source.
  • Axis titles should name the variable and its unit.
  • Set legend titles using aesthetic names such as color or fill.
  • labs() changes labels without changing data or mappings.
  • Alt text describes the chart, variables, and main pattern.

5.2 Add labels, reference lines, and highlights

An annotation directs attention to something worth noticing: one observation, a reference value, or a range. Its data source and placement determine whether it draws once or repeats across the table.

Label selected observations

geom_text(aes(label = species)) draws a label at every row’s mapped x and y position. geom_label() adds a box behind the text. A label for every point usually creates too much overlap, so give the label layer a small subset.

heaviest <- penguins[which.max(penguins$body_mass_g), ]

ggplot(penguins, aes(flipper_length_mm, body_mass_g)) +
  geom_point() +
  geom_label(
    data = heaviest,
    aes(label = species),
    vjust = -0.5
  )

The point layer uses the whole table. The label layer uses one row: a Gentoo with 221 mm flippers and a mass of 6,300 g. It inherits the x and y mappings, which its smaller table still contains.

geom_text(check_overlap = TRUE) skips labels that would overlap labels already drawn. The ggrepel functions geom_text_repel() and geom_label_repel() move labels apart and draw connectors back to their observations.

Position text relative to its anchor
ArgumentMeaning
hjust = 0Start the text at x
hjust = 0.5Center the text on x
hjust = 1End the text at x
vjust = 0Place the text’s bottom at y
vjust = 1Place the text’s top at y

nudge_x and nudge_y shift by data units. A vertical nudge of 100 on a gram axis means 100 g. Text geom size is in millimeters by default, while theme font sizes are in points. At the default 11-point theme size, the default text geom size is about 3.88 mm. fontface = "bold" changes the text face.

Draw one fixed annotation
annotate("text", x = 175, y = 6000,
         label = "Gentoo cluster", hjust = 0)

This supplies the coordinates directly. Using geom_text(aes(label = "Gentoo cluster")) with the full penguin table repeats the same text at all 342 measured positions. A constant label does not turn a row-based layer into a single annotation.

An arrow can use a segment:

annotate("segment", x = 200, y = 6000,
         xend = 215, yend = 5600,
         arrow = grid::arrow(length = grid::unit(2, "mm")))

A rectangle with xmin = 210, xmax = 235, ymin = -Inf, and ymax = Inf shades a full-height band. Set alpha = 0.2 and add the rectangle before points so observations remain visible.

Mark reference values

geom_hline(yintercept = 4201.8, linetype = "dashed") marks the penguins' mean mass, about 4,201.8 g. Compute it with mean(penguins$body_mass_g, na.rm = TRUE); without removing missing values the result is NA, so no useful reference line is drawn.

geom_vline(xintercept = ...) marks a vertical reference. geom_abline(intercept = ..., slope = ...) draws a straight line from its intercept and slope. Direct group labels can replace a legend when their positions clearly identify each group; remove the guide with theme(legend.position = "none") only once those labels are in place.

Key Takeaways

  • Give a label layer a subset when only selected observations need names.
  • Use annotate() for fixed coordinates and text that should be drawn once per panel.
  • Alignment describes how text sits around its anchor; nudging changes that anchor.
  • Reference-line functions specify intercepts directly.
  • Remove missing values when computing the mean used by a reference line.

5.3 Set the visual style with themes

A theme controls the non-data parts of a plot: fonts, background, grid lines, axis lines, legend placement, and spacing. Styling can improve readability while leaving the mapped data positions and fitted results unchanged.

Start with a complete theme

Complete themes replace the plot’s overall style. theme_gray() is the default gray panel with white grid lines. Other choices include theme_bw(), theme_light(), theme_linedraw(), theme_minimal(), theme_classic(), theme_dark(), and theme_void().

theme_classic() keeps axis lines and removes the grid. theme_void() removes axes, grids, and background. Choose the starting point that supplies useful structure for the figure.

Every complete theme accepts base_size, the base font size in points, and base_family, the font family. The default base size is 11. In ggplot2 4.0, ink, paper, and accent set foreground, background, and a highlight color. For example, theme_minimal(ink = "white", paper = "gray10") creates a dark style.

Change an individual element
Element functionWhat it controlsUseful arguments
element_text()Textsize, face, color, angle, hjust
element_line()Linescolor, linewidth, linetype
element_rect()Backgrounds and bordersfill, color
element_blank()Removal of an elementNo visible element

Put the complete theme before local changes:

p +
  theme_minimal(base_size = 14) +
  theme(
    panel.grid.minor = element_blank(),
    plot.title = element_text(face = "bold"),
    legend.position = "bottom",
    axis.text.x = element_text(angle = 45, hjust = 1)
  )

The base text becomes larger, minor grid lines disappear, the title becomes bold, the legend moves down, and x tick labels rotate. A complete theme added afterward would reset these earlier element settings.

Theme elements inherit from broader elements. axis.text.x inherits from axis.text, which inherits from text. A setting on text can therefore reach several kinds of labels; a more specific element can override it. Use the narrowest element that matches the part you intend to change.

Reuse a style
my_theme <- theme_minimal(base_size = 14) +
  theme(legend.position = "bottom")
p + my_theme

Store repeated settings to avoid retyping them for each plot. To set a session-wide default, use theme_set(theme_minimal()); set_theme() is the newer name available in ggplot2 4.0. Place the call near the top of a script so figures share a consistent starting style.

Keep text units straight

Theme font sizes are measured in points. A size explicitly supplied to geom_text() is measured in millimeters by default. About 3.88 mm matches 11 points because 1 mm is about 2.85 points.

Since ggplot2 4.0, text geoms with unset sizes follow the theme’s base size. Raising base_size can enlarge those labels as well as axes and titles. A layer with an explicit size = 3 stays fixed at that size, so adjust it separately when preparing a figure with larger text. Inspect both the plot labels and the theme text at the intended output size.

Key Takeaways

  • Themes control non-data styling, while scales control data encodings.
  • Apply a complete theme before custom theme() changes.
  • Use the appropriate element function for text, lines, backgrounds, or removal.
  • Theme elements inherit from broader settings.
  • Store a theme or set a session default for consistent figures.
  • Theme text uses points; explicitly sized text geoms use millimeters by default.

5.4 Export a reproducible figure and assemble panels

Saving a plot with code records which plot to export and how it should be sized. A figure that looks clear in the RStudio pane can look quite different at its final physical dimensions, so choose those dimensions as part of the plotting script.

Specify the plot and its size
ggsave(
  "penguin-mass.png",
  plot = p,
  width = 16, height = 10,
  units = "cm", dpi = 300
)

The extension selects PNG output. The canvas measures 16 × 10 cm. At 300 dots per inch, divide each centimeter dimension by 2.54 and multiply by 300: the result is about 1,890 × 1,181 pixels.

ggsave() defaults to the last displayed plot. If several plots are built in a script, pass plot = p so a later display cannot silently change the exported figure. Without width and height, the current plot-window dimensions are used. Resizing the pane would then change the result.

The default units are inches and the default raster resolution is 300 dpi. Specify units = "cm" or "mm" for metric dimensions; "px" is also supported. A relative output name is saved under the working directory, which is normally the project folder in an RStudio project.

Choose the format
FormatWhat is storedUseful setting
PDF or SVGVector shapesReports, print, and figures that must stay sharp when enlarged
PNGRaster pixelsWeb pages, slides, and dense plots with many points
JPEGCompressed raster pixelsCompression can blur thin lines and text

SVG output needs the svglite package. Very large point clouds can create bulky vector files because each point is stored separately; a PNG can be more practical. Higher raster resolution supplies more pixels at the same physical size, while vector shapes retain their edges as they are enlarged.

Plan readable text at the final size

Fonts and mark sizes have physical units. Saving the same plot on a larger canvas keeps text at the same point size, making it smaller relative to the whole figure. Increasing dpi alone does not enlarge that text relative to the canvas.

For slides, choose a suitable smaller physical canvas or raise the theme’s base_size. ggsave(scale = 2) doubles width and height; it does not double font sizes. Check the saved result at the size readers will see it.

Arrange separate plots with patchwork
library(patchwork)
p1 <- ggplot(penguins, aes(species, body_mass_g)) +
  geom_boxplot()
p2 <- ggplot(penguins, aes(body_mass_g)) +
  geom_histogram(binwidth = 200)
figure <- (p1 | p2) +
  plot_layout(widths = c(2, 1)) +
  plot_annotation(title = "Penguin body mass", tag_levels = "A")

With patchwork loaded, p1 + p2 or p1 | p2 puts plots beside each other, and p1 / p2 stacks them. (p1 | p2) / p3 places two above a third. Relative widths of 2 and 1 give the first panel twice the allocation of the second. guides = "collect" gathers matching guides, and plot_annotation() supplies a shared title and panel tags.

Save the assembled object with ggsave(plot = figure, ...) using actual dimensions in place of the omitted arguments. Facets split one plotting specification by a variable; patchwork arranges distinct plots that can use different geoms and axes.

Key Takeaways

  • Pass the intended plot and physical dimensions explicitly to ggsave().
  • Choose vector output for scalable shapes and raster output for a pixel image.
  • Raster dimensions depend on physical size and dpi.
  • A larger export canvas makes fixed-size text relatively smaller.
  • Patchwork arranges separate plots; facets split one plotting specification.

Data Visualization with ggplot2 examples

5 Walkthroughs

1

Build a plot and keep a working version

12 steps
Construct a small scatter plot, identify its components, and repair and store variations.
  1. 1
    IntroductionTurn readings into a plot

    A small table makes the whole plotting process visible. You will build a scatter plot of light level and plant height, identify the decisions inside it (the mapping of columns to position and the geom that draws the marks), then add and store a new layer. Each part can be changed without rebuilding the others.

    Keep the code in a script so you can rerun the setup and return to a version that works.

  2. 2
    ExampleCreate the observation table

    Load ggplot2 and create four observations:

    library(ggplot2)
    plants <- tibble::tibble(
      light = c(20, 35, 50, 65),
      height_cm = c(8, 11, 15, 18)
    )
    

    Each row describes one plant, and each column describes one variable. Light level will control horizontal position; height in centimeters will control vertical position. The variables already occupy separate columns, so the mapping can refer to them directly.

  3. 3
    ExplanationCreate the mapping

    Start the plot with its data and mappings:

    ggplot(plants, aes(x = light, y = height_cm))
    

    aes() says which column controls each position. This call establishes a panel and axes, but it has not specified any marks. An axis mapping can exist before a geom is present; the empty panel does not mean that the table has no observations.

  4. 4
    ExampleDraw the observations

    Add the point layer:

    ggplot(plants, aes(light, height_cm)) +
      geom_point()
    

    The first two unnamed mappings are x and y. Each point uses the row’s supplied values because the point geom’s stat is identity. Its position adjustment also leaves those positions unchanged. The upward pattern now becomes visible without asking the layer to compute an average or count.

  5. 5
    Key InsightRead the defaults too

    The visible points are only part of the specification. Continuous scales turn both numeric columns into positions and provide axes. Cartesian coordinates place those axes at right angles. The default theme supplies the gray panel and grid.

    These are active choices even though their functions are absent from the short call. You can replace one default without rebuilding the other components.

  6. 6
    ChallengeIdentify the component

    You want the same plant observations shown as a fitted trend instead of individual point marks. Which component must be changed?

    ---reveal---

    Change the geom to a smoother. It comes with a statistical calculation for the fitted trend. The data and x–y mapping can stay the same; changing the background theme would not replace the point marks with a trend.

  7. 7
    ExampleStore the first working plot

    Assign the scatter plot to an object:

    p <- ggplot(plants, aes(light, height_cm)) +
      geom_point()
    print(p)
    

    Assignment stores the plot; print() draws it. At the interactive console, typing p also displays it. Explicit printing is useful when the same code later moves into a loop, function, or sourced script, where automatic console printing cannot be relied on.

  8. 8
    ExampleKeep a second version

    Create a version with a straight fitted line:

    p_fit <- p + geom_smooth(method = "lm", se = FALSE)
    print(p_fit)
    

    The line is a second layer drawn above the points. The original object p still holds the point-only version. Keeping separate names lets you compare those two views without deleting or rewriting the original call.

  9. 9
    TipKeep the expression connected

    Put the joining + at the end of the line. It tells R that another component is coming. A new line starting with plus after an already complete expression is run separately and can fail.

    A pipe has a different job: it can feed a table into ggplot(). After entering the plot expression, use plus to add its layers. Check that operator before rewriting a layer that fails to attach.

  10. 10
    ChallengeRepair the missing column

    The plot call maps height_CM, and R reports that the object cannot be found. The table contains height_cm. What should you change, and should the error be silenced?

    ---reveal---

    Correct the mapping to height_cm; R treats uppercase and lowercase letters as different. This is an error preventing the requested plot, so warning-suppression arguments do not repair it. Rerun the corrected call.

  11. 11
    ChallengeChoose what to save

    You run p + geom_smooth() without assignment, then print p inside a loop. You want the trend included in every loop display. What must change?

    ---reveal---

    Store the extended result, such as p_fit <- p + geom_smooth(), and print p_fit in the loop. The smoother is a new layer, but adding it did not mutate p. Explicit printing and choosing the intended stored object solve separate parts of the problem.

  12. 12
    RecapCheck the working script

    Run the setup from a fresh point in the script, then print both stored versions. If one fails, return to the last working call and add only the failing change.

    Use the geom help page to check supported aesthetics before adding another property. This gives the next plot a tested starting point.

2

Choose mappings and reveal relationships

14 steps
Use a small sensor table to distinguish settings, grouping, distributions, and overlapping observations.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionChoose what the marks should show
  2. 2
    ExampleSet up the sensor data
  3. 3
    ExampleSeparate mapping from setting
  4. 4
    ChallengeFix the unexpected key
  5. 5
    ConnectionDecide which layers receive the group
  6. 6
    ExplanationChoose categories or intervals
  7. 7
    ExampleInspect a numeric distribution
  8. 8
    ChallengeRead the density axis
  9. 9
    ExampleKeep the series separate
  10. 10
    Key InsightChoose a view for the variable types
  11. 11
    TipChoose a remedy for crowding
  12. 12
    ChallengeHandle a hidden cluster
  13. 13
    ChallengeSeparate the findings
  14. 14
    RecapChoose the next plot deliberately
3

Follow a layer from rows to summaries

15 steps
Compute category shares, interpret boxplot limits, and arrange overlapping marks without losing their meaning.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionTrace the computation behind the marks
  2. 2
    ExampleStart with raw categories
  3. 3
    ExampleDraw existing totals directly
  4. 4
    ExampleCompute the denominator once
  5. 5
    ChallengeChoose the computation
  6. 6
    ExplanationRead the box before the whiskers
  7. 7
    ExampleCalculate the fences
  8. 8
    ChallengeFind observed endpoints
  9. 9
    Key InsightRead each uncertainty display correctly
  10. 10
    ExplanationChoose totals or shares
  11. 11
    ExamplePreserve measured values during jitter
  12. 12
    ChallengeRetain the comparison
  13. 13
    ConnectionKeep group boundaries in mind
  14. 14
    ChallengeDiagnose the all-one bars
  15. 15
    RecapInspect a summary in the right order
4

Change panels and axes without changing the question

17 steps
Compare facets, axis and color scales, and coordinate choices using positive-valued measurements.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionSeparate the view from the calculation
  2. 2
    ExampleBuild the shared plot
  3. 3
    ExplanationGive each subset a panel
  4. 4
    ChallengeRead a free-scale comparison
  5. 5
    TipPreserve grid alignment
  6. 6
    ExampleControl tick positions and units
  7. 7
    ExplanationSpace ratios evenly
  8. 8
    ChallengeConvert the same positions
  9. 9
    ExampleKeep site colors stable
  10. 10
    ExplanationChoose the scale family
  11. 11
    ChallengeRepair the guide without changing the cloud
  12. 12
    ExampleZoom after fitting
  13. 13
    Key InsightTransform at the intended stage
  14. 14
    ChallengePredict the changed model
  15. 15
    ConnectionMatch geometry to the units
  16. 16
    ChallengeKeep the intended fit and key
  17. 17
    RecapReview the display changes
5

Finish and export a clear report figure

18 steps
Add context and a selected annotation, apply a reusable style, and export and assemble plots reproducibly.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionPrepare a figure for someone else
  2. 2
    ExampleBuild the report plot
  3. 3
    ExampleGive the surrounding text a purpose
  4. 4
    ChallengeWrite useful alternative text
  5. 5
    ExampleSelect one observation to label
  6. 6
    ExampleHighlight a region behind the points
  7. 7
    ChallengeAvoid repeating a message
  8. 8
    ExplanationChoose a complete starting style
  9. 9
    ExampleApply custom elements after the theme
  10. 10
    ChallengeEnlarge the remaining small label
  11. 11
    ExampleRecord the export dimensions
  12. 12
    ExplanationChoose vector or raster output
  13. 13
    Key InsightA bigger canvas does not enlarge fonts
  14. 14
    ChallengeSelect a reproducible export
  15. 15
    ExampleCombine a different view
  16. 16
    TipRemove labels without losing their meaning
  17. 17
    ChallengeRepair the finished figure
  18. 18
    RecapInspect the exported result

Data Visualization with ggplot2 practice questions

50 Practice Questions in 5 sets

Set 1: Choose calculations and display settings10 Practice Questions

Question 1 of 10

A chart adds points and a fitted line from the same table. How many layers are present, and what plot components do they share?
  1. One layer with separate coordinates for each geom
  2. Two layers with a separate x scale for each geom
  3. One layer sharing only the underlying data table
  4. Two layers sharing the scales and coordinates
Show answerHide answer
Answer: D
Each geom call creates its own layer, even when both inherit the same data and mappings. The layers share the plot scales and coordinate system. A second geom does not automatically create another axis transformation or a separate coordinate system for its marks.

Question 2 of 10

A scatter plot globally maps both color and shape to site, and its smoother fits separate site lines. The report needs the same colored, shaped points but one overall straight fit. What mapping change meets that aim?
  1. Move only the color mapping into the point layer.
  2. Move both color and shape mappings into the point layer only.
  3. Move only the shape mapping into the point layer.
  4. Keep both mappings global and set the smoother to se = FALSE.
Show answerHide answer
Answer: B
Both discrete mappings can supply grouping inherited by the smoother. Moving both into the points retains their appearance while leaving one overall fit. Moving only color is insufficient because the remaining global discrete shape mapping can still divide the statistical layer into sites.

Question 3 of 10

A density curve is nearly flat beside a count histogram of the same measurements. How should the histogram be changed so their vertical quantities agree?
  1. Map its y to after_stat(density).
  2. Set the curve to adjust = 2.
  3. Map the histogram y to after_stat(count).
  4. Set the histogram to bins = 1.
Show answerHide answer
Answer: A
A density histogram has total bar area 1 and uses the same vertical quantity as the density curve. The default count mapping uses observation counts, so the heights are not comparable. Changing smoothing or bin number alone leaves the two layers on different vertical scales.

Question 4 of 10

A raw table has 12 "North" rows and 28 "South" rows. With aes(region, y = after_stat(prop)) + geom_bar(), both bars reach 1. What mapping change gives shares of all 40 rows?
  1. Add fill = region inside aes().
  2. Set position = "fill" in geom_bar().
  3. Add group = 1 inside aes().
  4. Add scale_y_continuous(limits = c(0, 1)).
Show answerHide answer
Answer: C
Discrete x values create separate groups, so each category is initially its own denominator and receives a proportion of 1. group = 1 puts both categories in one group, giving 12/40 and 28/40. Filling each separate stack still makes each stack total 1.

Question 5 of 10

Each bar should show the percentage composition of a different station, even though station sample sizes differ. What position adjustment makes that comparison?
  1. position = "stack"
  2. position = "dodge"
  3. position = "identity"
  4. position = "fill"
Show answerHide answer
Answer: D
Fill rescales each stack to height 1, so segment heights show shares within a station. Ordinary stacking preserves total counts, which leaves stations with different sample sizes at different heights. After filling, label the vertical axis as proportions or percentages.

Question 6 of 10

Bars use aes(fill = habitat). Adding scale_color_brewer(palette = "Set2") leaves their interiors unchanged. What scale should replace it?
  1. scale_fill_brewer(palette = "Set2")
  2. scale_color_gradient(low = "white", high = "blue")
  3. scale_fill_gradient(low = "white", high = "blue")
  4. scale_x_discrete(name = "Set2")
Show answerHide answer
Answer: A
The interiors are controlled by fill, so their palette must be changed with a fill scale. A color scale addresses the separate color aesthetic. A continuous gradient is also unsuitable here because habitat is a category, while Set2 supplies discrete category colors.

Question 7 of 10

A positive-valued x variable is shown with a straight fitted trend using method = "lm". The analyst wants the original-scale model retained but the horizontal display logarithmic. What component achieves this?
  1. scale_x_log10()
  2. aes(x = log10(x))
  3. coord_transform(x = "log10")
  4. scale_x_continuous(transform = "log10")
Show answerHide answer
Answer: C
A coordinate transformation happens after the model is fitted, so the original-scale linear model is retained and may look curved. A log position scale transforms values before the stat, fitting a different relationship. Directly mapping logged x also changes the values received by the model.

Question 8 of 10

A scatter plot has 600 rows. A fixed message must appear once at x = 8 and y = 20. How should the message be added?
  1. Use geom_text(aes(label = "Check sensor")) on all rows.
  2. Use annotate("text", x = 8, y = 20, label = "Check sensor").
  3. Use labs(caption = "Check sensor") below the plot.
  4. Use geom_text(aes(label = sensor_id)) on all rows.
Show answerHide answer
Answer: B
annotate() takes the fixed location and message directly, so the annotation is drawn once in the panel. A constant label in a text geom that inherits all 600 rows still repeats once per row. A caption places the message outside the panel instead of at the requested coordinates.

Question 9 of 10

A plot needs a minimal theme with minor grid lines removed. What component order retains the grid customization?
  1. theme(panel.grid.minor = element_blank()) + theme_minimal()
  2. theme_minimal() + theme(panel.grid.minor = element_line())
  3. theme_minimal() + theme(panel.background = element_blank())
  4. theme_minimal() + theme(panel.grid.minor = element_blank())
Show answerHide answer
Answer: D
Apply the complete theme first, then change its minor-grid element. A complete theme added last replaces earlier theme settings, so the removal would be reset. Removing the panel background targets a different element and does not request removal of minor grid lines.

Question 10 of 10

A PNG is exported at 18 × 12 cm and 300 dpi. It is exported again at 36 × 24 cm and the same dpi, with no plot styling changes. How do pixel dimensions and text proportions change?
  1. Both pixel dimensions double; text is smaller relative to the canvas.
  2. Both pixel dimensions double; text keeps the same relative size.
  3. Both pixel dimensions stay fixed; text becomes relatively smaller.
  4. Both pixel dimensions quadruple; text becomes relatively larger.
Show answerHide answer
Answer: A
At fixed dpi, doubling each physical dimension doubles the pixels along that dimension. Font sizes stay fixed in points, so the text occupies a smaller share of the larger canvas. The pixel area quadruples, but each width and height only doubles.
Set 2: Build and read a first plot10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

A plot uses geom_point() for sensor readings. What component turns a numeric temperature value into a color from a gradient?
  1. A color setting
  2. A position adjustment
  3. A color scale
  4. A facet variable
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A plot stored as p does not appear inside a for loop. What call should the loop use to display it?
  1. print(p)
  2. ggplot(p)
  3. p <- p
  4. library(p)
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A scatter plot should paint every point dark green and show no color legend. What point layer gives that result?
  1. geom_point(aes(color = "darkgreen"))
  2. geom_point(fill = "darkgreen")
  3. geom_point(aes(color = site))
  4. geom_point(color = "darkgreen")
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A lab records one row per sample with numeric length_mm. The analyst needs counts in 5 mm intervals. What layer and mapping should be used?
  1. aes(length_mm) with geom_bar(width = 5)
  2. aes(length_mm) with geom_histogram(binwidth = 5)
  3. aes(length_mm) with geom_density(adjust = 5)
  4. aes(length_mm) with geom_freqpoly(bins = 5)
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

group_id contains numeric codes 1, 2, and 3 for unrelated teams. What color mapping requests three category keys instead of a numeric color bar?
  1. aes(color = group_id)
  2. aes(color = as.numeric(group_id))
  3. aes(color = factor(group_id))
  4. aes(color = "group_id")
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A table contains one row per region and a column total_kg with its measured total. How should bars display those totals?
  1. Map region to x, then use the default geom_bar().
  2. Map region and total to x and y, then use geom_col().
  3. Map region and total to x and y, then use geom_bar().
  4. Map region to x, then use geom_histogram().
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

What does the usual shaded band around geom_smooth(method = "lm") describe?
  1. Uncertainty about the mean fitted trend
  2. The range holding 95% of single readings
  3. The span from lowest to highest reading
  4. The middle half of the response values
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A panel must be drawn for each device using the same plot, with panels wrapped into two columns. What component should be added?
  1. facet_grid(device ~ ., scales = "free")
  2. facet_wrap(~ device, nrow = 2)
  3. facet_grid(. ~ device, space = "free")
  4. facet_wrap(~ device, ncol = 2)
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

An axis contains proportions such as 0.18 and 0.42. How can it display them as "18%" and "42%" without changing the data?
  1. Use breaks = c(18, 42) in the scale.
  2. Use labels = scales::label_percent() in the scale.
  3. Multiply the plotted y values by 100 and keep a percent formatter.
  4. Use limits = c(18, 42) in the scale.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A plot maps treatment to color and shape and uses faint points. After labs(color = "Treatment group"), its guide splits. The report needs one guide with the new title and opaque keys, while data points stay faint. What edits meet those requirements?
  1. Give shape the same title and set the point-layer alpha to 1.
  2. Keep the titles different and override the guide alpha to 1.
  3. Give shape the same title and override the guide alpha to 1.
  4. Keep the titles different and move both guides to the bottom.
Show answerHide answer

Save this lesson to see this answer.

Set 3: Read the result of layered code10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

How does patchwork arrange the plots in (a | b) / c?
  1. Plot a beside b stacked on c
  2. Plots a and b above plot c
  3. Plots a, b, and c in a row
  4. Plots a, b, and c in a column
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A function returns a plot p. The caller runs p + geom_hline(yintercept = 25) and later prints p. Why is the line absent from that final display?
  1. A horizontal line must be added before the first geom.
  2. The extended plot was never assigned back to p.
  3. The stored plot cannot be extended outside its function.
  4. Printing a stored plot removes added reference layers.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

What aesthetic replaces the older use of size for setting line thickness in geom_line()?
  1. size
  2. stroke
  3. alpha
  4. linewidth
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

Rows contain numeric time, numeric temperature_c, and a character probe identifier for three probes. Rows are shuffled. What line mapping connects measurements in time order separately for each probe?
  1. geom_line(aes(time, temperature_c))
  2. geom_line(aes(time, temperature_c, group = probe))
  3. geom_path(aes(time, temperature_c, group = probe))
  4. geom_line(aes(time, temperature_c, group = 1))
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A group has Q1 = 40 mm and Q3 = 52 mm. Its two smallest observations are 20 and 25 mm, and its two largest are 68 and 73 mm. Under the usual boxplot rule, where do its whiskers end?
  1. At 25 mm and 68 mm
  2. At 22 mm and 70 mm
  3. At 20 mm and 73 mm
  4. At 40 mm and 52 mm
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A plot compares mass across four machine types. Repeated measurements should spread sideways, but each vertical position must retain its exact mass. What jitter settings meet that aim?
  1. width = 0, height = 0.15
  2. width = 0.15, height = 0.15
  3. width = 0.15, height = 0
  4. width = 0, height = 0
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A plot has two zones and two methods. Each combination has both status categories, with 30 complete observations and distinct x values per status. Color is globally mapped to status. With geom_smooth(method = "lm") and facet_grid(zone ~ method, scales = "free_y"), how many fits are drawn, and how is y shared?
  1. Eight fits; y is shared within each zone row.
  2. Four fits; y is shared within each zone row.
  3. Eight fits; y varies independently in every panel.
  4. Two fits; y is shared across all zone rows.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A log10 axis displays readings 3, 30, 300, and 3,000. How are those readings spaced, and what do the tick labels represent?
  1. Equally spaced; labels show their logarithms.
  2. Increasingly separated; labels show the original readings.
  3. Increasingly separated; labels show their logarithms.
  4. Equally spaced; labels show the original readings.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

Two reports map treatment to color and shape but use opposite factor orders. Their unnamed color vectors swap meanings, and renaming only the color guide splits the key. What repairs keep category colors stable and produce one guide?
  1. Keep unnamed colors and match the color and shape titles.
  2. Use named color values and keep the two guide titles different.
  3. Use named color values and matching titles for color and shape.
  4. Keep unnamed colors and move both guides below the plot.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A reference line should show the mean of mass_g, which contains missing values. mean(mass_g) returns NA. What change supplies the intended intercept?
  1. Compute mean(mass_g, na.rm = TRUE).
  2. Set na.rm = TRUE only on geom_hline().
  3. Use geom_hline(yintercept = 0) as the mean.
  4. Add na.rm = TRUE only to the point layer.
Show answerHide answer

Save this lesson to see this answer.

Set 4: Diagnose changes that alter a plot10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

What component changes background and grid styling without changing the plot's data encodings?
  1. The theme
  2. The stat
  3. The color scale
  4. The position adjustment
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A scatter plot and smoother worked before a continuous x-scale limit was added. Now a warning reports many removed rows and the fitted line changes. What diagnosis explains both changes?
  1. The scale cropped the display after the original fit was computed.
  2. The warning means the whole plot failed before any layer was drawn.
  3. The warning means the point data were lost but the fit used all rows.
  4. The scale excluded observations before the smoother was fitted.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A histogram changes from two broad peaks to many isolated spikes when binwidth changes from 40 to 2. How should the analyst investigate the distribution?
  1. Keep width 2, since narrow bins show the true shape.
  2. Compare several bin widths and check bin alignment.
  3. Keep width 40, since two peaks describe the population.
  4. Convert the measurement to a factor to remove spikes.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A pooled scatter plot slopes downward. After coloring by production line, every line's observations slope upward. What interpretation fits those displays?
  1. Coloring the observations changed their measured x and y values.
  2. Each within-line upward relationship rules out a pooled downward one.
  3. Between-line differences can reverse the pooled relationship.
  4. The pooled downward relationship establishes a negative causal effect.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

The raw data have regions East and West: East has 6 accepted and 4 rejected rows; West has 9 accepted and 21 rejected rows. Bars map x = region, fill = decision with position = "fill". What are the accepted heights?
  1. East 0.15 and West 0.225
  2. East 0.60 and West 0.30
  3. East 0.40 and West 0.60
  4. East 6 and West 9
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

Points map color locally to batch, and an ungrouped geom_smooth(method = "lm") draws one line with a narrow band. A colleague says this demonstrates that every batch has a precise upward trend. What is wrong with that reading?
  1. The fit is pooled, and its band describes the pooled mean trend.
  2. The fit is separate by batch, but its band shows individual ranges.
  3. The fit is pooled, and its band contains 95% of all observations.
  4. The fit is separate by batch, and its narrow band establishes causation.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A scientist compares width and height, both in millimeters. What coordinate setting makes a 10 mm change equally long on both axes?
  1. coord_cartesian(expand = FALSE)
  2. coord_flip()
  3. coord_cartesian(clip = "off")
  4. coord_fixed(ratio = 1)
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A plot will be embedded in a report for readers using screen readers. What should its alt text describe?
  1. The R package names, plot-object name, and export command
  2. The title alone, repeated exactly as printed
  3. The chart type, variables, and main visible pattern
  4. The full data table, every color name, and theme arguments
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A plot applies a bold-title customization, then theme_minimal(base_size = 16). Its title loses bold styling, while a text layer explicitly set to size = 3 stays small. What edits restore the title and enlarge that label?
  1. Put the complete theme first; apply bold styling afterward and leave the layer size fixed.
  2. Put the complete theme first; apply bold styling afterward and increase the layer size.
  3. Keep the current order; increase only base_size and leave the layer size fixed.
  4. Keep the current order; increase the layer size and leave the title customization before the theme.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A report script creates overview, then displays detail. It must export overview at a stable metric size independent of the plot pane. What call meets both requirements?
  1. ggsave("view.png", plot = overview, width = 15, height = 9, units = "cm")
  2. ggsave("view.png", width = 15, height = 9, units = "cm")
  3. ggsave("view.png", plot = overview, dpi = 300)
  4. ggsave("view.png", plot = detail, width = 15, height = 9, units = "cm")
Show answerHide answer

Save this lesson to see this answer.

Set 5: Repair plots in new situations10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

R cannot find ggplot() even though ggplot2 is installed. What should be run in the current session?
  1. library(ggplot2)
  2. library(ggplot)
  3. ggplot2()
  4. print(ggplot)
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A raw table has 80,000 rounded readings from two groups. The plot globally maps color to group and draws overlapping points. A report needs separate group panels, local cell counts, and only a count-based color guide. What redesign meets all three aims?
  1. Keep group color, use geom_bin_2d(), and facet by group.
  2. Remove group color, keep transparent points, and facet by group.
  3. Remove group color, use geom_bin_2d(), and facet by group.
  4. Remove group color, use geom_bin_2d(), and keep one pooled panel.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A summary table has one row per region–category combination and a count column n. The plot maps x = region, y = n, and fill = category. Some combinations are absent. The report needs side-by-side count bars with equal individual widths. What layer draws the stored counts and preserves those widths?
  1. geom_col(position = position_dodge())
  2. geom_col(position = position_dodge(preserve = "single"))
  3. geom_bar(position = position_dodge(preserve = "single"))
  4. geom_col(position = "fill")
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A scatter plot has separate group facets and a smoother in each. Switching from fixed scales to scales = "free_y" makes unequal vertical spreads look similar. A colleague says the spreads are now equal and the models were refitted to fewer rows. What is the correct reading?
  1. Panel stretching makes numeric spreads equal; the same rows still reach each fit.
  2. Panel stretching can hide spread differences; outside rows were removed before fitting.
  3. Panel stretching keeps heights directly comparable; outside rows were removed before fitting.
  4. Panel stretching can hide spread differences; the same rows still reach each fit.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A primary axis shows mass in grams and has sec_axis(~ . / 1000, name = "Mass (kg)"). A point lies at 3,600 g. A colleague wants that right-hand axis to also read a temperature series in degrees Celsius. What value belongs there, and can it serve both quantities?
  1. 3,600 kg; the linked axis cannot independently represent temperature.
  2. 3.6 kg; the linked axis cannot independently represent temperature.
  3. 3.6 kg; relabeling the axis lets it independently represent temperature.
  4. 3,600 kg; relabeling the axis lets it independently represent temperature.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

Small transparent plotted points make category legend keys hard to see. How can only the legend keys become larger and opaque?
  1. Use guide_legend(override.aes = list(size = 4, alpha = 1)).
  2. Set geom_point(size = 4, alpha = 1) for the plotted layer.
  3. Set theme(legend.position = "inside") for the guide.
  4. Use scale_color_manual() to change the category names.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

Count-bar tops fall between 10 and 100, yet adding y-scale limits of 10 to 100 makes the bars disappear. A colleague proposes coordinate limits with the same range and says the resulting visible lengths preserve the original bar ratios. What explains both problems?
  1. Scale limits exclude zero baselines; coordinate cropping retains the original visible length ratios.
  2. Scale limits change category counts; coordinate cropping retains the original visible length ratios.
  3. Scale limits exclude zero baselines; coordinate cropping can distort visible length ratios.
  4. Scale limits change category counts; coordinate cropping changes the statistical counts again.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

An axis currently displays area_m2. What label expresses the name and squared unit using R's mathematical label syntax?
  1. labs(y = "area_m2")
  2. labs(area_m2 = quote(Area ~ (m^2)))
  3. labs(y = quote(Area ~ (m^2)))
  4. labs(y = quote(Area ~ (m[2])))
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A plot maps length_mm to x and mass_g to y. The one-row table flagged contains those columns and name. A label must identify only that row and sit 50 g above it, while every original point keeps its position. What layer meets all requirements?
  1. geom_label(data = flagged, aes(label = name), nudge_x = 50)
  2. geom_label(data = flagged, aes(label = name), vjust = 50)
  3. geom_point(data = flagged, aes(label = name), position = position_nudge(y = 50))
  4. geom_label(data = flagged, aes(label = name), nudge_y = 50)
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

After theme_minimal(), a figure needs only minor grid lines removed, only x tick labels tilted 45 degrees, and its title bold. What customization targets exactly those three parts?
  1. theme(panel.grid = element_blank(), axis.text.x = element_text(angle = 45), plot.title = element_text(face = "bold"))
  2. theme(panel.grid.minor = element_blank(), axis.text.x = element_text(angle = 45), plot.title = element_text(face = "bold"))
  3. theme(panel.grid.minor = element_blank(), axis.text = element_text(angle = 45), plot.title = element_text(face = "bold"))
  4. theme(panel.grid.minor = element_blank(), axis.text.x = element_text(angle = 45), text = element_text(face = "bold"))
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

84 Key Terms, each with its definition

A

Aesthetic mapping
An aesthetic mapping connects a variable in the data to a visible property of marks, such as position, color, or shape.
In penguin data, mapping species to color assigns a different color to each species group and creates a guide.
Alpha
Alpha is opacity on a scale from 0 to 1, where 0 makes a mark invisible and 1 makes it fully opaque.
Setting a low alpha in a dense scatter plot can make darker regions reveal more overlap.
Alternative text
Alternative text describes the information in an image for people who cannot see it, including the plot’s variables and main pattern.
A scatter plot description can report its upward trend and identify the larger-bodied species cluster.
Annotation
An annotation adds explanatory information to a plot, such as a selected label, reference line, arrow, or highlighted region.
A shaded x interval can identify the range of readings that the figure’s title discusses.
Aspect ratio
An aspect ratio controls the physical relationship between x and y unit lengths, affecting the shape of the displayed coordinate space.
A fixed ratio of 1 makes a millimeter of width as long on the page as a millimeter of height.

B

Base size
Base size is a complete theme’s starting font size in points, from which its default text sizes are derived.
Raising base size enlarges theme text and, in ggplot2 4.0, text geoms whose size is unset.
Bin width
Bin width is the numeric span of an interval used to group continuous observations before counting them in a histogram.
Changing mass bins from 200 g to 20 g can reveal spikes caused by small local differences.
Boxplot outlier
A boxplot outlier is an observation beyond a 1.5-IQR fence, displayed separately from the whiskers under the usual rule.
An unusually heavy penguin can appear as an outlier while still being a valid measured animal.
Breaks
Breaks are data values chosen for tick marks or guide keys, separating where marks appear from how their labels are formatted.
Breaks every 10 mm can remain in place while their printed labels gain a unit suffix.

C

Caption
A caption supplies supporting information below a figure, often identifying the data source or another needed detail.
A caption naming the palmerpenguins package tells readers where the plotted observations came from.
Cartesian coordinates
Cartesian coordinates place x and y positions on perpendicular axes, giving ggplot2 its usual rectangular plotting space.
A mass-versus-length scatter plot uses horizontal length and vertical mass in one rectangular panel.
Clipping
Clipping prevents marks from being drawn outside the plotting panel, keeping overflowing elements inside its boundary.
Turning clipping off can let a carefully placed annotation extend into the surrounding plot margin.
Complete theme
A complete theme replaces the plot’s overall non-data style with a coordinated set of settings for its elements.
Apply theme_bw() before custom title styling so it does not reset the later bold title.
Computed variable
A computed variable is a value created by a statistical transformation and made available to mappings through after_stat().
A density histogram maps y to the binning stat’s density even though no input density column exists.
Confidence band
A smoother’s confidence band describes uncertainty about the fitted mean trend, usually at a 95% confidence level.
A narrow band around a line can coexist with individual observations spread widely around it.
Continuous gradient
A continuous gradient assigns a smoothly changing color to a numeric variable across its range of values.
Measured temperature can move from a low-value color to a high-value color along a color bar.
Coordinate transformation
A coordinate transformation changes how positions are displayed after stats, leaving the statistical calculation on its earlier values.
A log coordinate transformation can bend the display of a line fitted on the original x values.
Coordinate zoom
Coordinate zoom narrows the visible window after statistical calculations, preserving the data used to compute the result.
A close view of central x values can retain the smoother fitted to the entire measured sample.
Counting stat
A counting stat totals rows at each distinct position and provides computed values such as counts and group proportions.
A raw table of species names becomes one count per species before the bar layer draws its rectangles.

D

Density
Density describes a continuous distribution through a curve whose total area is 1, allowing shapes to be compared on a common scale.
A density curve uses area over an interval, so a height on its y axis is not an observation count.
Direct label
A direct label names a group near its marks so readers can identify it without repeatedly consulting a separate legend.
Names beside the ends of lines can replace a color legend when the links are clear.
Discrete color scale
A discrete color scale assigns separate colors to categories and shows a key for each category in its legend.
Treatment names need category colors even when they are stored using numeric group codes.
Distribution
A distribution describes which values a variable takes and how often they occur, revealing features such as center and spread.
A mass histogram can reveal a heavier cluster that is mostly associated with one species.
Diverging gradient
A diverging gradient uses different color directions around a meaningful midpoint to distinguish departures on either side.
Differences below and above zero can share a light midpoint and contrasting endpoint colors.
Dodge
Dodging places grouped marks beside one another at the same x location so their values can be compared separately.
Side-by-side species bars all start at zero, unlike the upper segments of a stacked bar.
Dpi
Dpi is dots per inch, a resolution setting used to relate a raster image’s physical dimensions to its pixel dimensions.
At a fixed centimeter size, a higher dpi creates more pixels without enlarging text relative to the canvas.

E

Element inheritance
Element inheritance lets specific theme elements receive properties from broader ones unless a more specific setting overrides them.
An x-axis tick label can inherit settings from axis text and then from the general text element.
Error
An error stops the requested operation because R cannot complete it, for example when a mapped column name is misspelled.
An unknown Length_mm column can stop a call when the actual column is named length_mm.
Expansion
Expansion is padding added beyond a scale’s data range to provide space around plotted marks at the panel edges.
Zero lower expansion can put the bottoms of count bars directly on the horizontal axis.

F

Facet
A facet is a panel showing a subset of the data using the same plotting instructions as the other panels in the figure.
Island facets split penguin data by island while every panel keeps the same flipper and mass mappings.
Fill
Fill is the aesthetic that controls the interior color of marks such as bars, boxes, areas, and point shapes 21–25.
A box can have a pale blue fill and a black outline so both visual properties remain distinct.
Fill position
Fill positioning rescales every stack to height 1, making the segments show proportions within that x group.
An island with 20 observations can be compared with one with 200 by their species shares.
Finding title
A finding title states the main pattern a figure communicates, helping readers see why the displayed comparison matters.
"Longer flippers accompany greater body mass" tells readers what to notice in the scatter plot.
Fixed aesthetic
A fixed aesthetic is a visual property set to one constant outside aes(), so it applies uniformly across a layer.
Setting color = "navy" in a point layer gives all its points navy without a color guide.
Fixed scales
Fixed facet scales keep axis ranges shared, so the same position represents the same value across the relevant panels.
A taller mass cloud in fixed-scale panels indicates a genuinely wider vertical range.
Free scales
Free facet scales allow ranges to differ across panels or grid rows and columns, making local variation easier to inspect.
A narrow-range group can fill its own panel when free y scales expand its vertical view.
Frequency polygon
A frequency polygon shows counts from numeric bins as a connected line, providing an unfilled view of a binned distribution.
Several species frequency polygons can share a panel without filled histogram bars covering them.

G

Geom
A geom is the geometric object that represents values in a plot, such as a point, line, bar, box, or text label.
The same numeric x and y mappings can feed point marks and a fitted trend in separate layers.
Global mapping
A global mapping is an aesthetic mapping supplied to ggplot() that layers inherit unless they override or disable it.
A global species color mapping makes both the points and a smoother use species groups.
Grammar of graphics
The grammar of graphics describes a plot as separate components that can be combined and changed independently.
The grammar explains how a point layer and a fitted-line layer can share one set of axes.
Grouping
Grouping divides a layer’s rows into subsets that are drawn or summarized separately, often from discrete aesthetic mappings.
Mapping a series identifier to group keeps separate temperature traces from being connected.

H

Histogram
A histogram groups numeric observations into intervals and draws bars to show how much data fall within each interval.
A 200 g bin width groups nearby penguin masses instead of counting every exact mass separately.

I

Identity stat
The identity stat passes supplied values through without summarizing them, allowing a geom to draw those values directly.
A column layer uses the existing total_kg values as bar heights instead of counting the rows.
Interquartile range
The interquartile range is Q3 minus Q1, measuring the spread of the middle half of the observations.
A larger IQR gives a taller vertical box and changes the distance used to locate outlier fences.

J

Jitter
Jitter adds small random shifts to positions, separating observations with repeated or rounded coordinates.
Horizontal jitter separates repeated mass points within species while zero vertical jitter keeps mass exact.

L

Layer
A layer combines data, aesthetic mappings, a geom, a statistical transformation, and a position adjustment in one plot.
A point layer shows individual readings, while another layer can highlight a selected subset.
Legend guide
A legend guide explains how visual properties such as color, shape, or size correspond to mapped data values.
A shared species guide can display both each group’s point shape and its assigned color.
Legend override
A legend override changes the appearance of guide keys independently of the appearance of plotted data marks.
Small transparent data points can have large opaque guide keys to make the species easier to identify.
Line plot
A line plot connects observations in x order within each group, making it useful for showing change over ordered time.
Separate probe groups let a line plot trace each instrument’s temperatures across the same months.
Local mapping
A local mapping is an aesthetic mapping supplied within one layer, where it adds to or overrides inherited mappings for that layer.
A color mapping inside only the point layer leaves an otherwise ungrouped smoother pooled.
Logarithmic scale
A logarithmic scale gives equal ratios equal spacing while allowing labels to show the original, positive data values.
Readings of 5, 50, and 500 are equally spaced even though their numerical differences grow.

M

Manual palette
A manual palette explicitly supplies the visual values assigned by a scale, with names available to tie colors to categories.
Named treatment colors remain consistent when two reports put the factor levels in opposite orders.
Median
The median is the middle of an ordered distribution, dividing its observations into lower and upper halves.
The line inside a species box marks its median mass even when the mean lies elsewhere.
Message
A message is informational feedback about a successful operation, often reporting a default choice made by a plotting function.
A histogram can report that it used 30 bins, inviting an explicit choice of bin width.

N

Nudge
A nudge shifts a mark by a fixed amount in data units, often to move a label away from its observation.
A vertical nudge of 100 on a gram axis places text 100 g above the point it describes.

O

Overplotting
Overplotting occurs when marks cover one another, hiding the number of observations or the concentration in a region.
Repeated rounded sensor values can produce a dark patch even when every row is drawn.

P

Panel strip
A panel strip is the facet label that identifies the subset displayed in that panel, usually by its variable value.
Using label_both changes a strip from "Adelie" to "species: Adelie" for a clearer identifier.
Path
A path connects observations in their row order, so its route depends on the sequence of records in the input data.
A route through recorded locations needs the visit order, even when its x coordinates go backward.
Physical dimensions
Physical dimensions are the saved figure’s width and height in units such as centimeters, independent of the plot pane’s current size.
Recording a 16 × 10 cm canvas makes repeated exports use the same shape after a pane resize.
Plot layout
A plot layout arranges separate plot objects within a shared figure, with control over rows, columns, relative sizes, and guides.
Patchwork can put two plots above a third while adding a shared title and panel letters.
Plot object
A plot object stores the data references, layers, and display settings needed to build a ggplot2 figure when it is drawn.
Saving a scatter plot as p lets a script create several labeled or faceted variations from it.
Plotmath expression
A plotmath expression uses R’s mathematical notation to format labels with features such as superscripts and subscripts.
The expression quote(Area ~ (m^2)) puts a raised 2 in the y-axis unit label.
Polar coordinates
Polar coordinates place values by radius and angle, allowing a bar-based display to be represented around a circle.
Mapping a stacked bar’s y values to angle produces slices whose shares come from its segments.
Position adjustment
A position adjustment arranges marks that would share a location after their statistical values have been computed.
Bar counts can be stacked, dodged, or filled without choosing a different counting stat.
Proportion
A proportion is a part divided by its total, so its interpretation depends on which observations form the denominator.
One overall group gives each species a share of all rows instead of a share of itself.

Q

Quartile
A quartile is a value marking a quarter boundary in an ordered distribution; Q1 and Q3 bound the middle half.
The lower and upper edges of a mass boxplot correspond to the first and third quartiles.

R

Raster image
A raster image stores a figure as pixels, so its resolution and physical dimensions determine the detail available in the saved image.
A PNG for slides needs enough pixels to keep its text readable at the intended display size.
Reference line
A reference line marks a specified comparison value or relationship, such as an average, target, or known straight line.
A dashed horizontal line at the available-data mean makes heavier and lighter observations easier to compare.

S

Scale
A scale translates data values into visual values and provides a guide, such as an axis or legend, to interpret that translation.
A continuous x scale positions lengths while its axis lets readers recover the millimeter values.
Scale limits
Scale limits restrict the displayed value domain and, for continuous position scales by default, exclude outside values before stats.
Narrow x-scale limits can change a smoother because some observations no longer reach the fit.
Scatter plot
A scatter plot places observations by two numeric variables, making the direction, shape, and spread of their relationship visible.
A flipper-length versus body-mass scatter plot places each measured penguin at its two values.
Secondary axis
A secondary axis gives a linked transformation of the primary axis values, presenting the same positions in another unit or form.
A gram axis can have a kilogram axis on the right by dividing primary values by 1,000.
Small multiples
Small multiples are repeated panels for related subsets, usually sharing a display structure that supports comparison.
The same scatter plot can be repeated for each species so crowded clusters no longer overlap.
Stack
Stacking places bar segments on top of one another at each x value, so their combined height represents the total.
An island bar can add the separate species counts into one visible sample-size total.
Statistical transformation
A statistical transformation computes the values a layer draws from its input rows, such as bin counts, quartiles, or a fitted trend.
A histogram stat counts observations inside intervals before the bar marks are drawn.

T

Text layer
A text layer draws labels from rows at mapped positions, allowing selected observations to be identified within a plot.
A one-row data table lets a label layer name the heaviest observation without labeling all points.
Theme
A theme controls non-data styling such as fonts, background, grids, legend placement, and spacing around the figure.
A minimal theme can simplify the surrounding lines while leaving the fitted trend unchanged.
Theme element
A theme element is an individual styled component, such as axis text, a grid line, or a background rectangle.
Changing axis.text.x rotates horizontal tick labels without rotating the title or legend text.
Tidy data
Tidy data organize each variable in its own column and each observation in its own row, giving mappings columns to refer to.
A long table with a year column lets year control color without a separate mapping for each year.
Two-dimensional binning
Two-dimensional binning groups observations into x–y cells and counts the rows in each cell to summarize local concentration.
A filled rectangular-cell plot can replace an unreadable scatter plot of tens of thousands of rows.

V

Vector image
A vector image stores geometric shapes, allowing lines and text outlines to stay sharp when the figure is enlarged.
A PDF figure can be enlarged in a report without exposing a fixed grid of source pixels.
Violin plot
A violin plot shows a group’s distribution through a mirrored density shape, revealing features that a boxplot may hide.
A wide part of a species violin marks a range with more concentrated mass measurements.

W

Warning
A warning reports an issue during an operation that can still produce a plot, such as dropped rows or a deprecated argument.
A missing-row warning on a scatter plot calls for checking which measurements could not be placed.
Whisker
A boxplot whisker reaches the most extreme observed value that is no farther than 1.5 IQR from its adjacent box edge.
An upper fence of 70 mm can produce a whisker at 68 mm if that is the last observed value inside it.

About this lesson

By StudeliReport a mistake

Make your own Study Materials

Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.

Get Started