ggplot2 Tutorial

Create clear, publication-ready charts with ggplot2

Scatter plots, bar charts, histograms, boxplots and more — plus themes, labels and exporting for reports.

ggplot2 cheat sheet Get help with your graphs

ggplot2 Boxplot in R: Complete Guide with Examples

Updated

This in-depth ggplot2 boxplot tutorial explains how to create and interpret box plots in R, from basic distribution summaries to grouped comparisons, notched boxplots, variable widths, jittered observations, custom outliers, facets and statistical summaries. Follow practical examples and download datasets to practise.

This lesson is part of the ggplot2 tutorial. The first examples use mpg, a dataset supplied with ggplot2. Later examples use fictional practice datasets provided with this lesson.

1. What is a boxplot in R?

A boxplot (also called a box-and-whisker plot) is a compact statistical graph that summarizes the distribution of a numeric variable. It is particularly useful for comparing the centre, spread and potential outliers of several groups. In ggplot2, the main function for drawing a boxplot is geom_boxplot().

A boxplot is useful when you want to:

  • Compare exam scores across classes or teaching methods.
  • Compare salaries, costs, sales or performance across departments.
  • Inspect the spread and skewness of a numeric variable.
  • Identify observations that are unusually far from the central range.
  • Compare distributions across categories without displaying every observation.
ggplot2 boxplot comparing exam score distributions across Control Treatment A and Treatment B groups
Boxplots compare the distribution of a continuous outcome across categories.

2. Create a basic boxplot with geom_boxplot()

Map a categorical variable to the x-axis and a numeric variable to the y-axis. The mpg dataset contains vehicle class and highway fuel economy.

library(ggplot2)

ggplot(mpg, aes(x = class, y = hwy)) +
  geom_boxplot()

Each box represents the distribution of highway fuel economy for one vehicle class. This is a useful first graph for comparing the typical values and variation among categories.

ggplot(mpg, aes(class, hwy)) +
  geom_boxplot(fill = "skyblue", colour = "grey25") +
  labs(
    title = "Highway fuel economy by vehicle class",
    x = "Vehicle class",
    y = "Highway miles per gallon"
  ) +
  theme_minimal()
Basic box and whisker plot showing median, quartiles, whiskers and potential outliers for three exam score groups
Illustrative boxplot using the downloadable exam-score practice data.

3. Understand the median, quartiles, IQR and whiskers

To interpret a boxplot correctly, understand its main components:

  • Median (Q2): the 50th percentile, shown by the line inside the box.
  • First quartile (Q1): the 25th percentile, at the lower edge of a vertical box.
  • Third quartile (Q3): the 75th percentile, at the upper edge of a vertical box.
  • Interquartile range (IQR): Q3 − Q1. The box contains the middle 50% of observations.
  • Whiskers: extend to the most extreme observations within the usual 1.5 × IQR fences.
  • Potential outliers: observations beyond the whisker endpoints, plotted individually by default.
Annotated boxplot identifying first quartile Q1 median third quartile Q3 interquartile range and whisker structure
The box represents the interquartile range, while whiskers and separately plotted points show values outside the central half of the data.

The whiskers do not necessarily extend to the minimum and maximum. Under the default Tukey rule, the lower and upper fences are:

Lower fence: Q1 − 1.5 × IQR

Upper fence: Q3 + 1.5 × IQR

The whiskers reach the most extreme observed values still inside those fences. The exact quartile calculation can depend on the quantile algorithm and software settings.

x <- mpg$hwy
quantile(x, probs = c(0, .25, .5, .75, 1), na.rm = TRUE)

Q1 <- quantile(x, .25, na.rm = TRUE)
Q3 <- quantile(x, .75, na.rm = TRUE)
IQR(x, na.rm = TRUE)

4. Identify and customize boxplot outliers

In a standard ggplot2 boxplot, observations beyond 1.5 times the IQR from a quartile are drawn as individual points. These are potential outliers under a statistical rule; they are not automatically incorrect observations.

# Default: display potential outliers
ggplot(mpg, aes(class, hwy)) +
  geom_boxplot()

# Change outlier appearance
ggplot(mpg, aes(class, hwy)) +
  geom_boxplot(
    outlier.colour = "red",
    outlier.shape = 16,
    outlier.size = 2.5
  )
Boxplot highlighting potential outlier observations beyond the 1.5 times interquartile range whisker limits
Points beyond the whiskers are flagged by the boxplot rule and should be investigated in context.

To hide the separately drawn outlier points, use outlier.shape = NA. This changes only their display; it does not remove those observations from the statistical calculation.

ggplot(mpg, aes(class, hwy)) +
  geom_boxplot(outlier.shape = NA) +
  geom_jitter(width = 0.15, alpha = 0.3)

Newer ggplot2 releases also provide an outliers argument for controlling whether outliers are retained in the layer output. Check your installed version before using newer arguments. Do not remove observations from an analysis simply to make a plot look cleaner.

5. Change boxplot colours, fill and line appearance

Use fill for the inside of each box and colour for its outline and median/whisker styling. Fixed values belong outside aes().

ggplot(mpg, aes(class, hwy)) +
  geom_boxplot(
    fill = "#90CAF9",
    colour = "#263238",
    linewidth = 0.7,
    outlier.colour = "#D1495B"
  ) +
  theme_minimal()

Map fill to a grouping variable when you want a different colour for each group.

ggplot(mpg, aes(class, hwy, fill = drv)) +
  geom_boxplot() +
  scale_fill_brewer(palette = "Set2") +
  labs(fill = "Drive type") +
  theme_minimal()

Use a restrained palette and keep the legend clear. Avoid using colour as decoration when it does not encode a meaningful variable.

6. Grouped and dodged boxplots

To compare several subgroups within each main category, map a second categorical variable to fill. ggplot2 can place the boxes side by side using position = position_dodge().

ggplot(mpg, aes(x = class, y = hwy, fill = drv)) +
  geom_boxplot(
    position = position_dodge(width = 0.8)
  ) +
  labs(
    title = "Highway fuel economy by class and drive type",
    x = "Vehicle class",
    y = "Highway miles per gallon",
    fill = "Drive type"
  ) +
  theme_minimal()

For a separate practice dataset, compare regions within quarters:

regional <- read.csv("regional_metrics.csv")

ggplot(regional,
       aes(x = quarter, y = value, fill = region)) +
  geom_boxplot(position = position_dodge(width = 0.8)) +
  theme_minimal()
Grouped boxplots comparing distributions for North South and East regions across four quarters
Dodged boxplots support comparisons across two categorical variables.

7. Overlay individual observations with jitter

A boxplot compresses many observations into a summary. Overlaying points makes sample size, clusters and unusual values more visible. Use geom_jitter() to move points slightly sideways so overlapping observations can be seen.

ggplot(mpg, aes(class, hwy)) +
  geom_boxplot(
    outlier.shape = NA,
    fill = "grey90"
  ) +
  geom_jitter(
    width = 0.15,
    alpha = 0.35,
    colour = "#2878B5"
  ) +
  theme_minimal()
Boxplots overlaid with semi-transparent jittered individual exam score observations for three groups
Jittered points reveal the distribution of individual observations behind each box.

For dense datasets, consider ggbeeswarm::geom_quasirandom() or geom_beeswarm(). These methods arrange points to reduce overlap more systematically.

install.packages("ggbeeswarm")
library(ggbeeswarm)

ggplot(mpg, aes(class, hwy)) +
  geom_boxplot(outlier.shape = NA) +
  geom_quasirandom(alpha = 0.45, width = 0.2) +
  theme_minimal()

8. Create horizontal boxplots

Horizontal boxplots are helpful when category labels are long or when comparing many groups. A common approach is to use coord_flip().

ggplot(mpg, aes(x = class, y = hwy)) +
  geom_boxplot(fill = "#A8DADC") +
  coord_flip() +
  labs(x = "Vehicle class",
       y = "Highway miles per gallon") +
  theme_minimal()
Horizontal box and whisker plots comparing exam score distributions across three groups
Horizontal orientation makes long category labels easier to read.

Depending on your ggplot2 version, you can also use the geom's orientation support by mapping the numeric variable to x and specifying orientation = "y". coord_flip() remains familiar and widely used.

9. Create notched boxplots

A notched boxplot adds a narrowing around the median. The notch is based on an approximate interval for the median, often described as median ± 1.58 × IQR / √n. It can provide a visual comparison of medians across groups.

ggplot(mpg, aes(class, hwy, fill = class)) +
  geom_boxplot(
    notch = TRUE,
    notchwidth = 0.5
  ) +
  guides(fill = "none") +
  theme_minimal()
Notched ggplot2 boxplots comparing median values and distributions across three groups
Notches focus attention on the median. Their overlap is a rough visual guide, not a replacement for a formal hypothesis test.

If a notch extends beyond the box, ggplot2 may display a warning or produce a visibly unusual shape. This can happen with small samples or particular distributions. Interpret notches cautiously.

10. Variable-width boxplots

By default, boxes have similar widths. Set varwidth = TRUE to make box widths proportional to the square root of the number of observations in each group. This gives a visual indication of relative sample size.

ggplot(mpg, aes(class, hwy)) +
  geom_boxplot(varwidth = TRUE) +
  labs(
    title = "Variable-width boxplots",
    x = "Vehicle class",
    y = "Highway miles per gallon"
  ) +
  theme_minimal()
Variable-width boxplots illustrating different group sample sizes through the widths of the boxes
Variable widths communicate relative group sizes; they do not represent the spread of the numeric values.

11. Create faceted boxplots

Use facet_wrap() or facet_grid() to create separate panels for another categorical variable. Facets can reduce clutter when a single chart contains many groups.

ggplot(mpg, aes(class, hwy, fill = class)) +
  geom_boxplot() +
  facet_wrap(~ drv) +
  guides(fill = "none") +
  labs(x = "Vehicle class",
       y = "Highway miles per gallon") +
  theme_minimal()

Use fixed scales when readers need to compare magnitudes across panels. Free scales can make within-panel patterns easier to see but make direct comparisons more difficult.

12. Add means and summary statistics to boxplots

A standard boxplot displays the median, not the mean. Add the mean explicitly when it is relevant to your analysis.

ggplot(mpg, aes(class, hwy)) +
  geom_boxplot() +
  stat_summary(
    fun = mean,
    geom = "point",
    shape = 23,
    size = 3,
    fill = "gold"
  ) +
  theme_minimal()

You can also calculate group summaries separately with dplyr:

library(dplyr)

mpg_summary <- mpg |>
  group_by(class) |>
  summarise(
    n = n(),
    mean_hwy = mean(hwy, na.rm = TRUE),
    median_hwy = median(hwy, na.rm = TRUE),
    sd_hwy = sd(hwy, na.rm = TRUE),
    .groups = "drop"
  )

mpg_summary

Do not confuse the mean marker with the median line. They describe different measures of central tendency and can differ substantially in skewed distributions.

13. Customize whiskers and boxplot statistical settings

The coef argument controls the whisker rule. The default is 1.5, meaning whiskers extend to the most extreme observations within 1.5 × IQR of the quartiles. Setting coef = 2 or coef = 3 uses wider fences.

# Default Tukey whisker rule
ggplot(mpg, aes(class, hwy)) +
  geom_boxplot(coef = 1.5)

# Wider whisker rule
ggplot(mpg, aes(class, hwy)) +
  geom_boxplot(coef = 3)

Use width to control box width, staplewidth to adjust whisker end caps where supported, and median.linewidth or related styling arguments in versions that provide them. For portable styling, linewidth, colour and fill are commonly used.

Changing coef changes which observations are shown as outliers; it does not change the raw dataset. State the whisker convention when it matters to the interpretation.

14. Draw boxplots from precomputed statistics

If your data already contain the five-number summary and whisker endpoints, use stat = "identity" with geom_boxplot(). The required aesthetics include ymin, lower, middle, upper and ymax.

summary_box <- data.frame(
  group = c("A", "B", "C"),
  ymin = c(10, 14, 12),
  lower = c(18, 21, 20),
  middle = c(25, 29, 27),
  upper = c(32, 36, 34),
  ymax = c(40, 44, 42)
)

ggplot(summary_box, aes(
  x = group,
  ymin = ymin,
  lower = lower,
  middle = middle,
  upper = upper,
  ymax = ymax
)) +
  geom_boxplot(stat = "identity", fill = "#90CAF9") +
  theme_minimal()

This is useful when a report supplies only summary statistics rather than individual observations. It does not allow ggplot2 to recover the original distribution or identify individual outliers. Do not invent whisker endpoints from quartiles if the source has not provided them.

15. Download boxplot practice datasets

Use these fictional datasets to practise basic, grouped and faceted boxplots. They are educational examples and do not represent real students, vehicles or regional performance.

scores <- read.csv("exam_scores.csv")

ggplot(scores, aes(group, score, fill = group)) +
  geom_boxplot() +
  guides(fill = "none") +
  labs(x = "Group", y = "Exam score") +
  theme_minimal()

For a grouped comparison using the regional dataset:

regional <- read.csv("regional_metrics.csv")

ggplot(regional, aes(quarter, value, fill = region)) +
  geom_boxplot(position = position_dodge(width = 0.8)) +
  labs(x = "Quarter", y = "Metric value", fill = "Region") +
  theme_minimal()

16. Interactive boxplot explorer

Change the group to see how the median, quartiles and potential outliers summarize a distribution. This small browser-based illustration is an educational aid; use geom_boxplot() in R for your own analysis.

17. Common boxplot mistakes and practice exercises

Common mistakes

  • Using two numeric variables: a standard grouped boxplot needs a numeric outcome and a grouping variable. For two numeric variables, consider a scatter plot.
  • Confusing whiskers with minimum and maximum: the default whiskers usually stop at the most extreme observations within 1.5 × IQR.
  • Calling every outlier an error: investigate unusual observations rather than deleting them automatically.
  • Confusing mean and median: the central line is the median. Add a separate mean marker if needed.
  • Hiding outliers and assuming they were removed: outlier.shape = NA hides their symbols but does not remove observations from the calculation.
  • Too many colours: use meaningful group colours and a readable legend.
  • Ignoring sample sizes: add sample counts or use varwidth = TRUE when group sizes matter.
  • Comparing free scales as if they were identical: free facet scales change the visual scale between panels.

Practice exercises

  1. Create a boxplot of mpg$hwy across vehicle classes.
  2. Colour the boxes by drv and explain what the groups represent.
  3. Make a horizontal boxplot using coord_flip().
  4. Create a notched boxplot and explain what the notch represents.
  5. Overlay jittered observations without duplicating the outlier symbols.
  6. Compare regions across quarters using dodged boxplots.
  7. Add the mean as a diamond-shaped point and distinguish it from the median.
  8. Compare the default whisker rule with coef = 3.

Continue learning ggplot2

Boxplots are often used with histograms, density plots and violin plots to investigate distributions from different perspectives. Continue with the other lessons in the ggplot2 tutorial.

ggplot2 FAQ

How do I create a boxplot in ggplot2?

Map a categorical variable to x and a numeric variable to y, then add geom_boxplot(), for example ggplot(mpg, aes(x = class, y = hwy)) + geom_boxplot().

What does the box in a boxplot represent?

The box extends from the first quartile (Q1, 25th percentile) to the third quartile (Q3, 75th percentile). Its height is the interquartile range (IQR).

What does the line inside a boxplot represent?

The line inside the box marks the median, or 50th percentile.

How are outliers identified in a boxplot?

The usual Tukey rule flags observations below Q1 − 1.5 × IQR or above Q3 + 1.5 × IQR. These are potential outliers, not automatically data errors.

How do I change boxplot colours in ggplot2?

Set fill outside aes() for one fixed colour, or map fill to a grouping variable inside aes() to colour groups separately.

How do I show individual points on a boxplot?

Add geom_jitter() or a beeswarm layer from ggbeeswarm. You can hide the boxplot's separately drawn outlier points with outlier.shape = NA to avoid duplication.

What is a notched boxplot?

A notched boxplot adds a notch around the median. The notch is an approximate visual interval for the median; substantial non-overlap can suggest a difference, but it is not a substitute for a formal analysis.

How do I make a horizontal boxplot?

Use coord_flip() after geom_boxplot(), or map the numeric variable to x and use the orientation setting where supported by your ggplot2 version.