Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 39 ยท Visualization

ggplot2 Basics: The Grammar of Graphics in R

Learn ggplot2 from scratch: the grammar of graphics, data and aes, geom_point, geom_line, geom_col, histograms, box plots, smoothers, color mapping versus setting, and layers.

ggplot2 is the most widely used plotting package in R. Instead of a menu of chart types, it gives you a grammar: a small set of parts that you combine to describe any chart. Once you know the parts, a scatter plot, a bar chart and a map follow the same recipe, and changing a chart (add a trend line, color by group, split into panels) is a matter of adding one more piece with +.

Install it with install.packages("ggplot2") and load it with library(ggplot2). It is also part of the tidyverse. If you have not seen the older base graphics system, you can still start here; the two do not depend on each other.

R does not run on this site, so the code is read-only and each chart is described in words. Run the code in R or RStudio to see it.

The parts of a plot

A plot is built from layers

Data A data frame
Aesthetics x, y, color, size
Geoms Points, lines, bars
Stats Counts, smooths

Every plot is data + aesthetics + at least one geom.

1 / 2

Your first plot

Three ingredients are required: the data, a mapping from columns to visual properties (aes()), and a geom that says how to draw the rows.

R
library(ggplot2)

ggplot(data = mtcars, mapping = aes(x = wt, y = mpg)) +
  geom_point()

ggplot() creates an empty canvas that knows the data and the default mapping. geom_point() adds a layer that draws one point per row, with wt on the x-axis and mpg on the y-axis. The result is the same cloud of 32 dots you would get from plot(mtcars$wt, mtcars$mpg), now with a gray grid background and automatic axis labels taken from the column names.

Experienced users drop the argument names: ggplot(mtcars, aes(wt, mpg)) + geom_point().

The + must be at the end of a line, not the start of the next one. A line starting with + is a syntax error, because R thinks the previous line was already complete.

Aesthetics: mapping data to appearance

An aesthetic is a visual property that can carry data: x, y, color, fill, size, shape, alpha (transparency), linetype. Put a column inside aes() and ggplot2 chooses the scale and draws the legend.

R
ggplot(mtcars, aes(wt, mpg, color = factor(cyl))) +
  geom_point(size = 3)

Now each cylinder count gets its own color, and a legend named factor(cyl) appears. factor() turns the number into categories; if you passed plain cyl, ggplot2 would treat it as a continuous variable and draw a gradient.

Mapping versus setting

This is the most common beginner confusion.

  • Mapping (inside aes()): the property depends on the data. aes(color = cyl).
  • Setting (outside aes()): one fixed value for all points. geom_point(color = "red").
R
geom_point(color = "red")          # all points red
geom_point(aes(color = "red"))     # NOT red: a legend entry labeled "red", in the default color

The second form maps the constant string "red" to the color aesthetic, so ggplot2 treats it as a category called "red" and picks its own color.

Choosing a geom

Each geom_*() function draws one kind of mark. The geom you need depends on the variables.

Question Geom Variables
Relationship of two numbers geom_point() x numeric, y numeric
Trend over time or order geom_line() x ordered, y numeric
Distribution of one number geom_histogram(), geom_density() x numeric
Compare a number across groups geom_boxplot(), geom_violin() x category, y numeric
Count of categories geom_bar() x category
Given heights per category geom_col() x category, y numeric
Trend line through a cloud geom_smooth() x, y numeric

Distributions

R
ggplot(mtcars, aes(mpg)) +
  geom_histogram(binwidth = 2, fill = "steelblue", color = "white")

ggplot(mtcars, aes(mpg)) +
  geom_density(fill = "steelblue", alpha = 0.4)

geom_histogram() counts rows in bins of width 2 (the default of 30 bins is rarely right, and ggplot2 prints a note saying so). geom_density() draws a smooth curve; alpha makes the fill see-through.

Bars: geom_bar versus geom_col

geom_bar() counts the rows for you. geom_col() draws bars of heights you already have.

R
ggplot(mtcars, aes(factor(cyl))) +
  geom_bar()                          # bar heights 11, 7, 14 (computed by ggplot2)

means <- aggregate(mpg ~ cyl, data = mtcars, FUN = mean)
ggplot(means, aes(factor(cyl), mpg)) +
  geom_col()                          # heights 26.66, 19.74, 15.10 (supplied by you)

Under the hood geom_bar() uses a stat (stat_count) that turns rows into counts, while geom_col() uses stat_identity, which leaves the data alone. Every geom has a default stat; you meet them mostly through geom_smooth() and geom_histogram().

Comparing groups

R
ggplot(mtcars, aes(factor(cyl), mpg)) +
  geom_boxplot()

ggplot(mtcars, aes(factor(cyl), mpg)) +
  geom_jitter(width = 0.15, height = 0)    # shows every point, nudged sideways

Overlay raw points on top of a box plot (add both geoms) so that readers see the data and not only the summary.

R
ggplot(economics, aes(date, unemploy)) +
  geom_line()

economics is a data set shipped with ggplot2 (US monthly economic series). For several lines, map a grouping variable: aes(date, value, color = series) or aes(group = series).

geom_smooth() adds a fitted trend with a confidence band:

R
ggplot(mtcars, aes(wt, mpg)) +
  geom_point() +
  geom_smooth(method = "lm", se = TRUE)    # straight line; se = FALSE hides the band

Without method, ggplot2 picks LOESS for small data sets and a GAM for large ones.

Layers share the mapping

The aes() in ggplot() is inherited by every layer, and a layer can add or override its own aesthetics:

R
ggplot(mtcars, aes(wt, mpg)) +                   # inherited by all layers
  geom_point(aes(color = factor(cyl))) +         # only the points are colored
  geom_smooth(method = "lm", color = "black")    # one overall line, not three

If you had put color = factor(cyl) into ggplot(aes(...)), geom_smooth() would draw three lines, one per group. That is useful when you want it, and confusing when you do not. Layers can also use different data: geom_text(data = labels_df, aes(label = name)).

Working with your own data

ggplot2 expects tidy data frames: one row per observation, one column per variable. A wide table (one column per year) must be reshaped into long form first, usually with tidyr::pivot_longer(). Many "how do I plot this?" questions turn out to be reshaping questions.

Save the last plot with ggsave("plot.png", width = 6, height = 4, dpi = 300); or store a plot in a variable (p <- ggplot(...) + ...), add to it later (p + theme_minimal()) and print(p) inside loops and functions.

What a stat does: a Python stand-in

The bar chart above relied on a stat: it summarized rows before drawing. Here is what happens in aggregate() and geom_bar(), reproduced in Python so that you can run it. This is a comparison, not R.

Python Python comparison: the counts and means behind the bars

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

  • Putting + at the start of a new line.
  • Using aes(color = "blue") when you mean color = "blue" outside aes().
  • Passing a numeric code (cyl, year) when you want categories; wrap it in factor().
  • Using geom_bar() with a y aesthetic. Use geom_col() or stat = "identity".
  • Plotting wide data. Reshape to long form first.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which three things does every basic ggplot2 chart need?

    The minimum is a data frame, a mapping of columns to aesthetics, and a geom that draws them.
  2. 2. What is the difference between geom_point(color = 'red') and geom_point(aes(color = 'red'))?

    Inside aes(), a value is data and gets a scale and legend. Outside, it is a fixed setting.
  3. 3. When do you use geom_col() instead of geom_bar()?

    geom_bar() counts rows itself; geom_col() draws the values you provide.
  4. 4. Why does ggplot(mtcars, aes(wt, mpg, color = cyl)) draw a continuous color bar?

    A numeric variable gets a continuous scale. Use factor(cyl) to get one color per category.

Summary

  • A ggplot is data + aes() mappings + geoms, combined with +.
  • Mapping (inside aes()) ties appearance to data; setting (outside) fixes it.
  • Pick the geom by the variables: points, lines, histograms, boxes, bars, smoothers.
  • geom_bar() counts; geom_col() uses given heights; layers inherit the top-level aes().
  • Use tidy, long data and factor() for category codes.

Next: Customizing ggplot2: Facets, Scales and Themes