Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 39 ยท Visualization

Customizing ggplot2: Facets, Scales, Labels and Themes

Make ggplot2 charts clear and professional: facet_wrap and facet_grid, scales and colors, labs, themes, axis formatting, annotations, flipping bars, combining plots and saving.

A default ggplot2 chart is a good draft, not a finished figure. The remaining 20 percent of the work (readable labels, a sensible color palette, one chart per group, a clean theme) is what makes a chart communicate. The good news is that all of it follows the same pattern from the previous lesson: you add one more piece with +.

R is not available on this site, so the code is read-only and the results are described. A small Python block at the end shows the idea behind facets. We reuse the built-in mtcars data throughout.

Start from a base plot

Store a plot in a variable and keep adding to it. This makes the experiments in this lesson easy to read:

R
library(ggplot2)

p <- ggplot(mtcars, aes(wt, mpg, color = factor(cyl))) +
  geom_point(size = 2.5)

Facets: one panel per group

Faceting splits a plot into small panels by a variable, all with the same axes, so that groups are easy to compare.

R
p + facet_wrap(~ cyl)                       # one panel per cylinder count, wrapped into a grid
p + facet_wrap(~ cyl, nrow = 1)             # all in a single row
p + facet_grid(am ~ cyl)                    # rows = transmission, columns = cylinders
p + facet_wrap(~ cyl, scales = "free_y")    # each panel gets its own y-axis range

facet_wrap(~ var) lays the panels out in a wrapped ribbon; facet_grid(rows ~ cols) builds a strict matrix with the second variable across the top. By default every panel shares the same scales, which is what you want for honest comparison; scales = "free" is useful when panels have very different ranges, but readers can then misjudge sizes. Facets are usually better than drawing 8 overlapping colors.

Labels

Replace default labels (column names) with human-readable ones using labs():

R
p + labs(
  title    = "Heavier cars use more fuel",
  subtitle = "32 cars from the 1974 Motor Trend road tests",
  x        = "Weight (1000 lbs)",
  y        = "Miles per gallon",
  color    = "Cylinders",
  caption  = "Source: built-in mtcars data"
)

A good title states the finding, not just the topic. The legend title is set through the aesthetic name (color, fill, size).

Scales: axes and colors

Every aesthetic has a scale that controls how data values become visuals. The names follow scale_<aesthetic>_<type>.

R
p + scale_x_continuous(limits = c(0, 6), breaks = 0:6)
p + scale_y_continuous(labels = scales::label_number(accuracy = 1))
p + scale_y_log10()                                   # log axis
p + scale_color_brewer(palette = "Set1")              # ColorBrewer palettes
p + scale_color_viridis_d()                           # colorblind-safe discrete colors
p + scale_color_manual(values = c("4" = "tomato", "6" = "gold", "8" = "steelblue"))

Useful companions: scales::percent, scales::dollar and scales::comma format numbers as 45%, $1,200 and 1,200. Pass them as labels = scales::percent.

Prefer a colorblind-safe palette: scale_color_viridis_d() (and _c() for continuous data) or the Okabe-Ito colors. About 8 percent of men have some form of color-vision deficiency, and red versus green is the classic trap.

Zooming versus removing data. limits in a scale (or xlim()) drops the values outside the range before any statistics are computed, so a smoother or box plot changes. coord_cartesian(xlim = c(2, 4)) only zooms the view and keeps all data in the calculation.

Themes

A theme controls everything that is not data: background, grid lines, fonts, legend position. Start from a complete theme and tweak it.

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

theme_gray() is the default; theme_minimal() and theme_bw() are popular for reports. Settings come in the form part = element_*(): element_text() for text, element_line() for lines, element_rect() for boxes and element_blank() to remove a part. Set a theme for the whole session with theme_set(theme_minimal()).

Coordinates and ordering

coord_flip() swaps the axes, which is the easiest way to make long category labels readable on a bar chart:

R
ggplot(mtcars, aes(factor(cyl))) +
  geom_bar() +
  coord_flip()

Categories are drawn in factor level order, which is alphabetical by default. To sort bars by size, reorder the factor, for example with forcats::fct_reorder(name, value) or fct_infreq() for counts.

Annotations and reference lines

R
p +
  geom_hline(yintercept = mean(mtcars$mpg), linetype = "dashed") +
  annotate("text", x = 5, y = 22, label = "average mpg", hjust = 1) +
  geom_vline(xintercept = 3, color = "gray50")

annotate() places one-off text or shapes without needing a data frame. To label every point from a data frame column, use geom_text(aes(label = name)), or ggrepel::geom_text_repel() to avoid overlaps.

Combining and saving

The patchwork package puts plots side by side with an operator:

R
library(patchwork)
p1 <- ggplot(mtcars, aes(mpg)) + geom_histogram(binwidth = 2)
p2 <- ggplot(mtcars, aes(wt, mpg)) + geom_point()
p1 + p2             # side by side
p1 / p2             # stacked

Save with ggsave(), which defaults to the last plot shown:

R
ggsave("fuel-economy.png", plot = p, width = 7, height = 4.5, dpi = 300)
ggsave("fuel-economy.pdf", plot = p, width = 7, height = 4.5)   # vector, sharp at any size

Choose the size in inches for the place the figure will appear, so that text stays readable: 7 inches wide is a full page; 3.5 inches fits one column of a two-column journal.

A checklist for a clear chart

  1. A title that states the finding; axis labels with units.
  2. Facets rather than 6+ colors.
  3. A colorblind-safe palette; meaning is never carried by color alone.
  4. Gridlines light; no chart junk (3D, heavy borders).
  5. Sorted categories; flipped bars for long names.
  6. The y-axis starts at zero for bars (always) and for lines when zero is meaningful.
  7. Direct labels or a legend close to the data, not both.

What facets do: a Python stand-in

facet_wrap(~ cyl) splits the data by group and draws the same chart for each part. This Python block does the splitting and prints the summary that each panel would show. It is a comparison, not R.

Python Python comparison: small multiples by group

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Common mistakes

  • Setting limits to zoom a plot with a fitted line; the fit changes. Use coord_cartesian().
  • Forgetting factor() so that the legend is a gradient.
  • Writing theme(legend.position = "bottom") and then theme_minimal() after it: the later complete theme resets your tweaks. Put theme_*() first.
  • Saving with the screen size: always pass width, height and dpi.
  • Using free scales in facets without telling the reader.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which function builds a strict rows-by-columns grid of panels?

    facet_grid(rows ~ cols) places one variable on rows and another on columns. facet_wrap() wraps a single variable into a ribbon.
  2. 2. How do you change the legend title for the color aesthetic?

    labs() takes the aesthetic name (color, fill, size...) to set both axis and legend titles.
  3. 3. What is the difference between xlim() and coord_cartesian(xlim = ...)?

    Scale limits drop out-of-range rows, which changes smoothers and summaries. Coordinate limits just crop the view.
  4. 4. Which is the best way to make long category names on a bar chart readable?

    Horizontal bars give long labels room to breathe.

Summary

  • Add pieces with +: facets for groups, labs() for text, scale_*() for axes and colors, theme_*() for the look.
  • facet_wrap() for one variable, facet_grid() for two; keep scales shared unless you have a reason.
  • Use colorblind-safe palettes; zoom with coord_cartesian(), filter with scale limits.
  • Reorder factors to sort bars; coord_flip() helps long labels.
  • Save with ggsave(width, height, dpi); combine with patchwork.

Next: Choosing the Right Chart