- Learn
- Computer Science & IT
- Data Science & AI
- Data Analysis with R
- Data Visualization with ggplot2
Data Visualization with ggplot2
IntermediateLesson 2 of 7 in Data Analysis with R Course
What you will learn
- 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 graphicsName the components every ggplot2 plot is made of and read an existing chart as a combination of them.
- Write, store and debug a ggplot2 callWrite ggplot2 code with correct syntax, add layers in the right order, keep plots in objects, and use errors, warnings and messages to fix problems.
- Describe a plot as components of the grammar of graphics
- 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 valuesDistinguish mapping a variable inside aes() from setting a constant, and use color, fill, shape, size, alpha and group correctly.
- Show the distribution of one variableUse 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 variablesPick geoms by the types of the variables, combine several geoms in one plot, and handle extra variables and overplotting.
- Map variables to aesthetics or set fixed values
- 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 geomIdentify 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 smoothersRead and build boxplots, plot group summaries with stat_summary(), and add and interpret trend lines with geom_smooth().
- Arrange overlapping marks with position adjustmentsChoose between stacking, filling, dodging, identity, jittering and nudging for marks that share a position.
- Work with the stat behind each geom
- 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 facetsUse facet_wrap() and facet_grid(), decide between shared and free scales, and judge when facets work better than color.
- Control axes with position scalesSet axis titles, breaks, labels, limits and expansion, use log and other transformations, and format numbers and dates.
- Choose color scales and adjust legendsPick suitable discrete and continuous color scales, assign colors manually, and control legend position, titles and keys.
- Zoom and choose the coordinate systemZoom without losing data, swap or fix axes, and use polar and transformed coordinates where they help.
- Split a plot into small multiples with facets
- 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 plotUse 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 regionsLabel 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 themesApply 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 layoutsExport plots with ggsave() at a chosen size, resolution and format, and combine several plots into one figure with patchwork.
- Write labels and titles that explain the plot
Data Visualization with ggplot2 study guide
1Build 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.
| Component | Question it answers |
|---|---|
| Stat | What values must be computed? |
| Position adjustment | How should overlapping marks be arranged? |
| Scale | How do values become positions, colors, or sizes? |
| Coordinates | How are positions placed on the page? |
| Facets | Which subsets get separate panels? |
| Theme | How 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
| Feedback | What happened | What to do |
|---|---|---|
| Message | The plot ran and reports a choice, such as histogram bins. | Decide whether to specify the choice yourself. |
| Warning | The plot ran, but rows were dropped or a feature needs attention. | Read the reason and check the affected data or code. |
| Error | The 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.
2Map 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
| Goal | Code inside a point layer | Result |
|---|---|---|
| Color by species | aes(color = species) | Species get colors and a legend. |
| Make every point blue | color = "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
fillfor interiors andcolorfor points, lines, and outlines. - Use
linewidthfor lines,sizefor points and text, andstrokefor 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.
| Display | Input to the counting step | Meaning of adjacent bars |
|---|---|---|
| Bar chart | Separate categories | Different named groups |
| Histogram | Numeric intervals | Neighboring 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 andgeom_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
| Variables | Useful geoms | What you can compare |
|---|---|---|
| Two numeric | geom_point(), with an optional smoother | Direction, shape, and spread of a relationship |
| Numeric and categorical | geom_boxplot(), geom_violin(), grouped density curves | Group centers, spreads, or distribution shapes |
| Two categorical | Stacked or filled bars, geom_count() | Counts or shares of combinations |
| Numeric over ordered time | geom_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.
3Use 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
| Geom | Default stat | Values drawn |
|---|---|---|
| Point, line, column | Identity | Supplied values |
| Bar | Count | Number of rows at each category |
| Histogram, frequency polygon | Bin | Counts within numeric intervals |
| Density | Density | A smoothed distribution |
| Boxplot | Boxplot | Quartiles, whiskers, and outliers |
| Smooth | Smooth | A 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 andgeom_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:
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.
| Position | What the bar heights show | Main comparison |
|---|---|---|
"stack" | Counts added within each x | Totals and composition |
"fill" | Each stack rescaled to height 1 | Within-x shares |
"dodge" | Counts placed side by side | Individual groups from zero |
"identity" | Counts at the same x, overlapping | Requires 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.
4Control 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 setting | What 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 shown | Example scale | Meaning |
|---|---|---|
| Unordered categories | scale_color_brewer(palette = "Set2") | A distinct color for each group |
| A continuous measurement | scale_color_viridis_c() | A continuous progression |
| Discrete categories with viridis | scale_color_viridis_d() | Separate sampled colors |
| Binned measurements | scale_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 instruction | Data used by the smoother | Visible x window |
|---|---|---|
scale_x_continuous(limits = c(190, 220)) | Only the 230 measured rows in range | 190–220 mm |
coord_cartesian(xlim = c(190, 220)) | All 342 measured rows | 190–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.
5Communicate 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
colororfill. 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
| Argument | Meaning |
|---|---|
hjust = 0 | Start the text at x |
hjust = 0.5 | Center the text on x |
hjust = 1 | End the text at x |
vjust = 0 | Place the text’s bottom at y |
vjust = 1 | Place 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 function | What it controls | Useful arguments |
|---|---|---|
element_text() | Text | size, face, color, angle, hjust |
element_line() | Lines | color, linewidth, linetype |
element_rect() | Backgrounds and borders | fill, color |
element_blank() | Removal of an element | No 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
| Format | What is stored | Useful setting |
|---|---|---|
| PDF or SVG | Vector shapes | Reports, print, and figures that must stay sharp when enlarged |
| PNG | Raster pixels | Web pages, slides, and dense plots with many points |
| JPEG | Compressed raster pixels | Compression 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
1Build a plot and keep a working version
12 steps
- 1IntroductionTurn 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.
- 2ExampleCreate 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.
- 3ExplanationCreate 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. - 4ExampleDraw 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.
- 5Key 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.
- 6ChallengeIdentify 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.
- 7ExampleStore 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, typingpalso 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. - 8ExampleKeep 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
pstill holds the point-only version. Keeping separate names lets you compare those two views without deleting or rewriting the original call. - 9TipKeep 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. - 10ChallengeRepair the missing column
The plot call maps
height_CM, and R reports that the object cannot be found. The table containsheight_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. - 11ChallengeChoose what to save
You run
p + geom_smooth()without assignment, then printpinside 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 printp_fitin the loop. The smoother is a new layer, but adding it did not mutatep. Explicit printing and choosing the intended stored object solve separate parts of the problem. - 12RecapCheck 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.
2Choose mappings and reveal relationships
14 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionChoose what the marks should show
- 2ExampleSet up the sensor data
- 3ExampleSeparate mapping from setting
- 4ChallengeFix the unexpected key
- 5ConnectionDecide which layers receive the group
- 6ExplanationChoose categories or intervals
- 7ExampleInspect a numeric distribution
- 8ChallengeRead the density axis
- 9ExampleKeep the series separate
- 10Key InsightChoose a view for the variable types
- 11TipChoose a remedy for crowding
- 12ChallengeHandle a hidden cluster
- 13ChallengeSeparate the findings
- 14RecapChoose the next plot deliberately
3Follow a layer from rows to summaries
15 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionTrace the computation behind the marks
- 2ExampleStart with raw categories
- 3ExampleDraw existing totals directly
- 4ExampleCompute the denominator once
- 5ChallengeChoose the computation
- 6ExplanationRead the box before the whiskers
- 7ExampleCalculate the fences
- 8ChallengeFind observed endpoints
- 9Key InsightRead each uncertainty display correctly
- 10ExplanationChoose totals or shares
- 11ExamplePreserve measured values during jitter
- 12ChallengeRetain the comparison
- 13ConnectionKeep group boundaries in mind
- 14ChallengeDiagnose the all-one bars
- 15RecapInspect a summary in the right order
4Change panels and axes without changing the question
17 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionSeparate the view from the calculation
- 2ExampleBuild the shared plot
- 3ExplanationGive each subset a panel
- 4ChallengeRead a free-scale comparison
- 5TipPreserve grid alignment
- 6ExampleControl tick positions and units
- 7ExplanationSpace ratios evenly
- 8ChallengeConvert the same positions
- 9ExampleKeep site colors stable
- 10ExplanationChoose the scale family
- 11ChallengeRepair the guide without changing the cloud
- 12ExampleZoom after fitting
- 13Key InsightTransform at the intended stage
- 14ChallengePredict the changed model
- 15ConnectionMatch geometry to the units
- 16ChallengeKeep the intended fit and key
- 17RecapReview the display changes
5Finish and export a clear report figure
18 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionPrepare a figure for someone else
- 2ExampleBuild the report plot
- 3ExampleGive the surrounding text a purpose
- 4ChallengeWrite useful alternative text
- 5ExampleSelect one observation to label
- 6ExampleHighlight a region behind the points
- 7ChallengeAvoid repeating a message
- 8ExplanationChoose a complete starting style
- 9ExampleApply custom elements after the theme
- 10ChallengeEnlarge the remaining small label
- 11ExampleRecord the export dimensions
- 12ExplanationChoose vector or raster output
- 13Key InsightA bigger canvas does not enlarge fonts
- 14ChallengeSelect a reproducible export
- 15ExampleCombine a different view
- 16TipRemove labels without losing their meaning
- 17ChallengeRepair the finished figure
- 18RecapInspect the exported result
Data Visualization with ggplot2 practice questions
Set 1: Choose calculations and display settings10 Practice Questions
Question 1 of 10
Show answerHide answer
Question 2 of 10
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?Show answerHide answer
Question 3 of 10
Show answerHide answer
Question 4 of 10
aes(region, y = after_stat(prop)) + geom_bar(), both bars reach 1. What mapping change gives shares of all 40 rows?Show answerHide answer
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
Show answerHide answer
Question 6 of 10
aes(fill = habitat). Adding scale_color_brewer(palette = "Set2") leaves their interiors unchanged. What scale should replace it?Show answerHide answer
Question 7 of 10
method = "lm". The analyst wants the original-scale model retained but the horizontal display logarithmic. What component achieves this?Show answerHide answer
Question 8 of 10
Show answerHide answer
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
Show answerHide answer
Question 10 of 10
Show answerHide answer
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
geom_point() for sensor readings. What component turns a numeric temperature value into a color from a gradient?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
p does not appear inside a for loop. What call should the loop use to display it?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
length_mm. The analyst needs counts in 5 mm intervals. What layer and mapping should be used?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?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
total_kg with its measured total. How should bars display those totals?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
geom_smooth(method = "lm") describe?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
device using the same plot, with panels wrapped into two columns. What component should be added?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
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?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
(a | b) / c?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
p. The caller runs p + geom_hline(yintercept = 25) and later prints p. Why is the line absent from that final display?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
geom_line()?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
geom_smooth(method = "lm") and facet_grid(zone ~ method, scales = "free_y"), how many fits are drawn, and how is y shared?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
mass_g, which contains missing values. mean(mass_g) returns NA. What change supplies the intended intercept?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
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
binwidth changes from 40 to 2. How should the analyst investigate the distribution?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
x = region, fill = decision with position = "fill". What are the accepted heights?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
overview, then displays detail. It must export overview at a stable metric size independent of the plot pane. What call meets both requirements?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
ggplot() even though ggplot2 is installed. What should be run in the current session?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
area_m2. What label expresses the name and squared unit using R's mathematical label syntax?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
Aesthetic mapping
Alpha
Alternative text
Annotation
Aspect ratio
B
Base size
Bin width
Boxplot outlier
Breaks
C
Caption
Cartesian coordinates
Clipping
Complete theme
theme_bw() before custom title styling so it does not reset the later bold title.Computed variable
after_stat().Confidence band
Continuous gradient
Coordinate transformation
Coordinate zoom
Counting stat
D
Density
Direct label
Discrete color scale
Distribution
Diverging gradient
Dodge
Dpi
E
Element inheritance
Error
Length_mm column can stop a call when the actual column is named length_mm.Expansion
F
Facet
Fill
Fill position
Finding title
Fixed aesthetic
aes(), so it applies uniformly across a layer.color = "navy" in a point layer gives all its points navy without a color guide.Fixed scales
Free scales
Frequency polygon
G
Geom
Global mapping
ggplot() that layers inherit unless they override or disable it.Grammar of graphics
Grouping
H
Histogram
I
Identity stat
total_kg values as bar heights instead of counting the rows.Interquartile range
J
Jitter
L
Layer
Legend guide
Legend override
Line plot
Local mapping
Logarithmic scale
M
Manual palette
Median
Message
N
Nudge
O
Overplotting
P
Panel strip
label_both changes a strip from "Adelie" to "species: Adelie" for a clearer identifier.Path
Physical dimensions
Plot layout
Plot object
p lets a script create several labeled or faceted variations from it.Plotmath expression
quote(Area ~ (m^2)) puts a raised 2 in the y-axis unit label.Polar coordinates
Position adjustment
Proportion
Q
Quartile
R
Raster image
Reference line
S
Scale
Scale limits
Scatter plot
Secondary axis
Small multiples
Stack
Statistical transformation
T
Text layer
Theme
Theme element
axis.text.x rotates horizontal tick labels without rotating the title or legend text.Tidy data
Two-dimensional binning
V
Vector image
Violin plot
W
Warning
Whisker
- 1R and RStudio
- 2Data Visualization with ggplot2
- 3Transforming Data with dplyr
- 4Tidy Data and Data Import in R
- 5Strings and Factors in R
- 6Joins in R
- 7Exploratory Analysis in R
About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.