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 Geoms and Statistical Transformations: A Step-by-Step Guide

Updated

Geoms decide what visual marks a chart uses; stats calculate or transform data before those marks are drawn. Learn how they work together, when to use each geom, and how to choose the correct statistical transformation.

This lesson is part of the ggplot2 tutorial. The examples use mpg, a dataset included with ggplot2. You can run the code after loading the package.

The key distinction: a geom determines what is drawn (points, bars, lines, boxes). A stat determines whether the data is calculated or transformed before it is drawn (counts, bins, summaries or fitted trends). A ggplot2 layer brings these parts together.

1. Geom versus stat: understand the two jobs

Imagine that you have a spreadsheet containing 200 vehicles. You want to show the relationship between engine size and highway fuel economy. A scatter plot is appropriate: each vehicle is represented by one point. In this case, the geom draws points and the stat simply uses the supplied observations.

Now imagine that you want to show how many vehicles belong to each vehicle class. Your data contains one row per vehicle, but it does not contain a column with the number of vehicles in each class. ggplot2 must count the rows first. The bar geom draws the bars, while the count stat calculates their heights.

Geom: what gets drawn?

Points, bars, lines and boxes are different ways to display information.

Stat: what gets calculated?

A statistical transformation can turn individual rows into counts or summaries.

For most everyday plots, you do not need to specify the stat yourself. ggplot2 chooses a default that suits the geom. However, understanding the default helps you avoid common mistakes.

2. Choose a geom for the question you want to answer

Start with your analytical question, not with a favourite chart type. Different geoms answer different questions.

Your questionUseful geomWhat it displays
How are two numeric variables related?geom_point()One point per observation
How does a value change over time?geom_line()Connected observations in order
How many observations are in each category?geom_bar()Counts calculated from rows
What are the supplied values for each category?geom_col()Heights taken from a y column
How is one numeric variable distributed?geom_histogram()Counts within numeric intervals
How does a distribution vary by group?geom_boxplot()Median, quartiles and potential outliers
What is the overall trend?geom_smooth()An estimated smooth or fitted relationship
Quick rule: use points for individual observations, bars for category comparisons, histograms for numeric distributions, lines for ordered data and boxplots for comparing distributions.

3. Points and lines: show observations and ordered patterns

Scatter plots with geom_point()

Use geom_point() when each row is an observation and you want to compare two numeric variables. In mpg, displ is engine displacement and hwy is highway fuel economy.

library(ggplot2)

ggplot(mpg, aes(x = displ, y = hwy)) +
  geom_point()

Each vehicle becomes one point. The x and y coordinates come directly from the data. The default point geom does not need to calculate a category count or a histogram bin.

Improve the scatter plot

ggplot(mpg, aes(displ, hwy, colour = class)) +
  geom_point(size = 2.5, alpha = 0.7) +
  labs(
    title = "Engine size and highway fuel economy",
    x = "Engine displacement (litres)",
    y = "Highway miles per gallon",
    colour = "Vehicle class"
  )

Scatter plot: one point per row

Useful for seeing relationships, clusters and unusual observations.

Line charts with geom_line()

Use geom_line() when observations have a meaningful order, such as dates, months or time points. The line connects observations in x order.

ggplot(economics, aes(x = date, y = unemploy)) +
  geom_line()

The economics dataset is also included with ggplot2. This example shows unemployment over time. A line chart is suitable because the date variable provides a natural order.

Line chart: connect ordered values

Use a line when the sequence itself matters.

Do not connect unrelated categories. A line implies an order or continuity. For unordered categories, a bar chart or point chart is often more appropriate.

4. geom_bar() versus geom_col(): counts or supplied values?

This is one of the most important geom distinctions for beginners.

geom_bar(): count the rows

By default, geom_bar() uses stat_count(). You supply a categorical variable on x; ggplot2 counts how many rows belong to each category and uses those counts as bar heights.

# Count how many vehicles are in each class
ggplot(mpg, aes(x = class)) +
  geom_bar()

You do not need to calculate the counts first. ggplot2 does that work for you.

geom_bar(): automatic counts

The height of each bar is calculated from the number of rows.

geom_col(): use values already calculated

Use geom_col() when your data already contains the values you want to display. It uses stat_identity(), which means the y values are passed through without being counted.

# A small summary table created by you
class_summary <- data.frame(
  class = c("compact", "midsize", "suv"),
  mean_hwy = c(28, 25, 19)
)

ggplot(class_summary, aes(x = class, y = mean_hwy)) +
  geom_col()

geom_col(): supplied values

The bar heights come from the y column in your summary table.

Side-by-side comparison

Featuregeom_bar()geom_col()
Default statstat_count()stat_identity()
Input requiredCategory observationsCategory and numeric y value
Calculates counts?Yes, by defaultNo
Typical purposeFrequency of categoriesPre-calculated totals, averages or other values
How to choose:
  1. If your data has one row per person, product or event and you want the number in each category, use geom_bar().
  2. If your data already has one row per category and a column containing the height you want, use geom_col().

5. Histograms: understand numeric distributions

A histogram shows how numeric observations are distributed. It divides a continuous variable into intervals called bins, counts the observations in each bin and draws a bar for each interval.

ggplot(mpg, aes(x = hwy)) +
  geom_histogram()

Unlike a bar chart of categories, the x-axis of a histogram represents a numeric scale. The bars touch because the intervals are adjacent parts of that scale.

Control the bin width

The binwidth argument controls the width of each interval. A smaller bin width creates more, narrower bars. A larger bin width creates fewer, wider bars.

# Narrower bins
ggplot(mpg, aes(hwy)) +
  geom_histogram(binwidth = 2, fill = "steelblue",
                 colour = "white")

# Wider bins
ggplot(mpg, aes(hwy)) +
  geom_histogram(binwidth = 5, fill = "darkorange",
                 colour = "white")

Narrow bins

Shows more detail, but may look irregular.

Wide bins

Shows the broad shape, but can hide detail.

Choose bins thoughtfully

There is no single bin width that is best for every dataset. Try a few reasonable widths and consider whether the overall shape, clusters and tails are visible. Also consider the sample size: a small dataset may not support many narrow bins.

ggplot(mpg, aes(hwy)) +
  geom_histogram(
    binwidth = 3,
    boundary = 0,
    fill = "#3b82f6",
    colour = "white"
  ) +
  labs(
    title = "Distribution of highway fuel economy",
    x = "Highway miles per gallon",
    y = "Number of vehicles"
  )

6. Density plots: a smoothed view of a distribution

A density plot is another way to examine the distribution of a numeric variable. Instead of showing counts in separate bins, it estimates a smooth curve representing the distribution's shape.

ggplot(mpg, aes(x = hwy)) +
  geom_density(fill = "skyblue", alpha = 0.6)

The curve is based on a statistical estimate, not simply a line joining the raw observations. The amount of smoothing is influenced by the bandwidth.

# Compare distributions by vehicle class
ggplot(mpg, aes(x = hwy, colour = class,
                fill = class)) +
  geom_density(alpha = 0.15)

Density: smooth distribution shape

Useful for comparing the shape and spread of numeric distributions.

Interpretation note: density is not the same as a count. A density curve is scaled as an estimated probability density; its total area is approximately one for each group under the usual default.

7. Boxplots: compare distributions across groups

A boxplot summarises a numeric variable using its median, quartiles and potential outliers. It is useful when you want to compare a distribution across categories.

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

The box shows the middle 50% of the data, from the first quartile to the third quartile. The line inside the box marks the median. Whiskers extend to values within the usual 1.5 × interquartile-range rule; points beyond them are shown as potential outliers.

Reading a boxplot

Compare medians, spread and potential outliers between groups.

Compare groups using colour

ggplot(mpg, aes(x = class, y = hwy, fill = class)) +
  geom_boxplot(show.legend = FALSE) +
  labs(
    x = "Vehicle class",
    y = "Highway miles per gallon",
    title = "Highway fuel economy by vehicle class"
  )

Use boxplots when the distribution matters. If you only want to compare a single average or total, a summary chart may be clearer.

8. Smooth trend lines with geom_smooth()

geom_smooth() adds an estimated trend to a plot. It is often combined with points so that readers can see both the individual observations and the overall pattern.

ggplot(mpg, aes(x = displ, y = hwy)) +
  geom_point() +
  geom_smooth()

By default, ggplot2 chooses a smoothing method based on the size of the dataset. The shaded band represents the default confidence interval. You can hide it with se = FALSE.

Use a linear model

ggplot(mpg, aes(displ, hwy)) +
  geom_point() +
  geom_smooth(method = "lm", se = FALSE)

method = "lm" fits a linear model. It is useful when a straight-line relationship is a reasonable summary. Do not assume that a linear trend is appropriate for every dataset.

Use a smoother for a flexible trend

ggplot(mpg, aes(displ, hwy)) +
  geom_point(alpha = 0.6) +
  geom_smooth(method = "loess", se = TRUE)

LOESS can follow a curved pattern more flexibly, particularly in smaller datasets. The appropriate method depends on the data size, shape and analytical objective.

Points with a fitted trend

The points show observations; the curve summarises the trend.

9. How statistical transformations work

A stat takes the data available to a layer and calculates values needed for drawing. The output from the stat is then passed to the geom.

Think of a layer as a small processing pipeline:
  1. Input: the original data and aesthetic mappings.
  2. Stat: calculate or transform values, if required.
  3. Geom: draw the visual marks using the stat output.
  4. Position adjustment: arrange marks where necessary, for example stacking bars.

Examples of common default geom-stat combinations are:

GeomDefault statWhat the stat does
geom_point()stat_identity()Uses supplied observations without calculating a summary.
geom_bar()stat_count()Counts observations in each x category.
geom_col()stat_identity()Uses supplied y values directly.
geom_histogram()stat_bin()Groups numeric observations into bins and counts them.
geom_boxplot()stat_boxplot()Calculates boxplot statistics.
geom_smooth()stat_smooth()Estimates a trend and, by default, its uncertainty band.

This is why a histogram does not simply draw one bar for every raw observation. Its stat first calculates the bins and counts.

10. Understand stat_count() and stat_identity()

stat_count(): calculate category frequencies

stat_count() counts how many observations fall into each x category. It is the default stat used by geom_bar().

# These are equivalent for the usual count bar chart
ggplot(mpg, aes(class)) +
  geom_bar()

ggplot(mpg, aes(class)) +
  geom_bar(stat = "count")

You can also inspect the counts before plotting by calculating a summary table with R. This is useful when you need to reuse the values elsewhere.

class_counts <- as.data.frame(table(mpg$class))
names(class_counts) <- c("class", "n")

ggplot(class_counts, aes(class, n)) +
  geom_col()

stat_identity(): use the values supplied

stat_identity() does not calculate counts or summaries. It passes the supplied values through to the geom. This is the default stat for geom_col() and geom_point().

# These are equivalent for supplied y values
ggplot(class_summary, aes(class, mean_hwy)) +
  geom_col()

ggplot(class_summary, aes(class, mean_hwy)) +
  geom_col(stat = "identity")
Remember: use stat_count() when you want ggplot2 to count rows. Use stat_identity() when your data already contains the values to draw.

11. Calculate summaries with stat_summary()

Sometimes you have individual observations but want to display a summary for each group, such as the mean or median. stat_summary() calculates a summary within groups and displays it using a chosen geom.

Show the mean for each vehicle class

ggplot(mpg, aes(x = class, y = hwy)) +
  stat_summary(
    fun = mean,
    geom = "col",
    fill = "steelblue"
  )

Here, the input data contains individual vehicles. The stat calculates the mean highway fuel economy for each class, and the column geom displays those means.

Show the median as a point

ggplot(mpg, aes(x = class, y = hwy)) +
  stat_summary(
    fun = median,
    geom = "point",
    colour = "red",
    size = 3
  )

Show mean and standard error

mean_se <- function(x) {
  data.frame(
    y = mean(x, na.rm = TRUE),
    ymin = mean(x, na.rm = TRUE) -
      sd(x, na.rm = TRUE) / sqrt(sum(!is.na(x))),
    ymax = mean(x, na.rm = TRUE) +
      sd(x, na.rm = TRUE) / sqrt(sum(!is.na(x)))
  )
}

ggplot(mpg, aes(class, hwy)) +
  stat_summary(fun.data = mean_se, geom = "pointrange")

For more advanced reporting, make sure the summary statistic and uncertainty measure match your research question. A standard error is not the same as a standard deviation or a confidence interval.

12. Geoms and stats are combined in layers

A ggplot layer is not just a geom. It combines data, aesthetic mappings, a stat, a geom and a position adjustment. The geom_ functions provide convenient defaults, but you can change the stat when necessary.

# A point layer: raw observations are drawn as points
ggplot(mpg, aes(displ, hwy)) +
  geom_point()

# A bar layer: counts are calculated and then drawn
ggplot(mpg, aes(class)) +
  geom_bar()

# A smooth layer: a trend is estimated and drawn
ggplot(mpg, aes(displ, hwy)) +
  geom_smooth(method = "lm")

Specify a stat explicitly

Most of the time, the default is best. You can still write the stat explicitly when teaching, checking or controlling a layer.

ggplot(mpg, aes(class)) +
  geom_bar(stat = "count")

ggplot(mpg, aes(displ, hwy)) +
  geom_point(stat = "identity")

Use a stat function directly

Some stats have their own helper functions. For example, stat_summary() makes it clear that a layer is calculating a summary, rather than simply drawing every raw observation.

ggplot(mpg, aes(class, hwy)) +
  stat_summary(fun = mean, geom = "point",
               colour = "red", size = 3)

13. A practical workflow for selecting geoms and stats

  1. Identify the type of variable. Is it categorical, numeric, a date or an ordered sequence?
  2. Decide what should be displayed. Individual observations, counts, a distribution, a summary or a trend?
  3. Select a geom. Points, bars, columns, histogram, density, boxplot or line?
  4. Check the default stat. Does ggplot2 need to count, bin, summarise or fit a model?
  5. Check the data structure. Does each row represent an observation, or have you already aggregated the data?
  6. Add labels and visual settings. Use clear axis labels, colours and titles.
  7. Check the interpretation. Confirm that the chart displays the quantity you intended.
Example decision: You have a table with three columns: department, employee_id and salary.
  • To count employees in each department, use geom_bar(aes(x = department)).
  • To display the average salary by department after calculating the averages, use geom_col() with the summary table.
  • To compare the full salary distributions by department, use geom_boxplot() on the original employee-level data.

14. Common mistakes and troubleshooting

1. Using geom_bar() with an already calculated y value

If your data already contains a total or mean, geom_bar() will try to count observations rather than use that y value. Use geom_col() instead.

# Correct for an existing summary column
ggplot(class_summary, aes(class, mean_hwy)) +
  geom_col()

2. Using geom_col() without a y mapping

geom_col() needs a y value. If you only provide a category and want a frequency count, use geom_bar().

3. Confusing a histogram with a category bar chart

Use geom_histogram() for numeric measurements that need to be divided into bins. Use geom_bar() for discrete categories that need to be counted.

4. Choosing an unsuitable histogram bin width

Very narrow bins can make a distribution look noisy. Very wide bins can hide important features. Try several widths and explain the choice when it matters.

5. Treating a density curve as a count

A density plot shows an estimated distribution, not the number of observations in each interval. Use a histogram when frequency counts are the main message.

6. Using a line chart for unordered categories

A line connects values in sequence. If the x variable has no meaningful order, a line may suggest a relationship that does not exist.

7. Misreading the shaded area around geom_smooth()

The shaded area is an uncertainty band around the fitted trend, not a range containing every observation. Use se = FALSE to hide it when it distracts from the main message.

8. Ignoring missing or invalid values

Warnings about removed rows should be investigated. Check missing values and the ranges of the variables before deciding whether to filter or transform the data.

9. Function or object not found

Load ggplot2 with library(ggplot2). Check variable names with names(mpg); R is case-sensitive.

15. Practice exercises

Use the mpg dataset to complete these tasks. Try writing the code before opening the suggested solutions.

  1. Create a scatter plot of engine displacement against highway fuel economy.
  2. Count the number of vehicles in each class using geom_bar().
  3. Create a summary data frame containing three categories and their supplied values, then display those values using geom_col().
  4. Create a histogram of hwy using a bin width of 3.
  5. Compare the highway fuel economy distributions of vehicle classes using a boxplot.
  6. Add a linear trend line to a scatter plot using geom_smooth(method = "lm").
  7. Calculate and display the mean hwy value for each class using stat_summary().
  8. Explain why geom_bar() and geom_col() are not interchangeable in every situation.
Show suggested solutions
# 1. Scatter plot
ggplot(mpg, aes(displ, hwy)) +
  geom_point()

# 2. Count by class
ggplot(mpg, aes(class)) +
  geom_bar()

# 3. Display supplied values
example_summary <- data.frame(
  category = c("A", "B", "C"),
  value = c(12, 18, 9)
)
ggplot(example_summary, aes(category, value)) +
  geom_col()

# 4. Histogram
ggplot(mpg, aes(hwy)) +
  geom_histogram(binwidth = 3)

# 5. Compare distributions
ggplot(mpg, aes(class, hwy)) +
  geom_boxplot()

# 6. Linear trend
ggplot(mpg, aes(displ, hwy)) +
  geom_point() +
  geom_smooth(method = "lm")

# 7. Mean by class
ggplot(mpg, aes(class, hwy)) +
  stat_summary(fun = mean, geom = "point",
               colour = "red", size = 3)

16. What to learn next

After understanding geoms and stats, move on to position adjustments, scales, labels and themes. Position adjustments control how marks are arranged, while scales and themes help make the chart accurate, readable and visually consistent.

Key takeaway: choose a geom based on the visual mark and analytical question. Check the stat to understand what ggplot2 calculates before drawing. In particular, remember: geom_bar() counts, geom_col() uses supplied values, and geom_histogram() bins numeric data.

Next step: Continue with the next lesson using the navigation at the bottom of this page, or return to the ggplot2 tutorial overview.

ggplot2 FAQ

What is a geom in ggplot2?

A geom is the geometric object used to display data, such as points, bars, lines, boxplots, histograms or text.

What is a stat in ggplot2?

A stat is a statistical transformation that processes the data before it is displayed. Examples include counting categories, calculating histogram bins and estimating a smooth trend.

What is the difference between geom_bar() and geom_col()?

geom_bar() counts observations in each category by default. geom_col() uses y values that are already present in your data.

What is the difference between geom_histogram() and geom_bar()?

geom_histogram() groups numeric values into intervals and counts observations in each interval. geom_bar() normally counts observations in discrete categories.

What does stat = identity mean?

stat = 'identity' tells ggplot2 to use the supplied y values as they are, without calculating a new summary such as a count.

Can I use a stat with a different geom?

Yes. Geoms and stats are separate parts of a layer. You can select a stat explicitly with stat =, or use a stat function such as stat_summary() when it suits the task.

Why does geom_smooth() show a shaded area?

By default, geom_smooth() displays a confidence interval around the estimated trend. Use se = FALSE to hide the shaded interval.