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 Cheat Sheet: Functions, Geoms and Scales

Updated

Keep the most useful ggplot2 syntax in one place. Use this quick reference when building charts, customizing aesthetics or exporting graphics.

This page is a quick reference, not a replacement for the full ggplot2 tutorial. Follow the links in each section for detailed explanations and examples.

Basic plot structure

library(ggplot2)

ggplot(data = mpg, aes(x = displ, y = hwy)) +
  geom_point()
ElementPurpose
ggplot(data, aes(...))Start a plot and set default data/mappings
aes()Map variables to visual properties
geom_*()Choose the mark or chart type
stat_*()Calculate a statistical transformation
scale_*()Control mapping from data values to visual values
coord_*()Change the coordinate system or viewing window
facet_*()Split the plot into panels
theme()Style non-data plot elements

Aesthetic mappings

AestheticWhat it controlsExample
x, yHorizontal and vertical positionaes(x = displ, y = hwy)
colourPoint, line or outline colouraes(colour = class)
fillInterior colour of filled geomsaes(fill = drv)
sizeSize of points or linesaes(size = cty)
shapePoint symbolaes(shape = drv)
alphaTransparencyaes(alpha = cty)
groupDefines which observations are connected/groupedaes(group = class)

Remember: Put data-driven mappings inside aes(). Put fixed settings outside it, for example geom_point(colour = "blue"). Read the aesthetics lesson.

Common geoms

FunctionUseTypical syntax
geom_point()Scatter plotgeom_point()
geom_bar()Count observationsgeom_bar()
geom_col()Plot pre-calculated valuesgeom_col()
geom_histogram()Numeric distributiongeom_histogram(binwidth = 3)
geom_line()Connect ordered valuesgeom_line()
geom_boxplot()Compare distributionsgeom_boxplot()
geom_density()Smoothed distributiongeom_density()
geom_violin()Distribution shape by groupgeom_violin()
geom_smooth()Add a fitted trendgeom_smooth(method = "lm")
geom_text()Draw labels from datageom_text(aes(label = model))

See the dedicated lessons for scatter plots, bar charts, histograms, line graphs, boxplots and density and violin plots.

Scales, titles and labels

labs(
  title = "Plot title",
  subtitle = "Short explanation",
  x = "X-axis label",
  y = "Y-axis label",
  colour = "Group",
  caption = "Source: ..."
)

scale_colour_manual(
  values = c("group A" = "steelblue",
             "group B" = "firebrick")
)

scale_fill_viridis_d()
  • scale_x_continuous() and scale_y_continuous(): numeric axes.
  • scale_x_discrete() and scale_y_discrete(): categorical axes.
  • scale_colour_manual() and scale_fill_manual(): manually assign discrete colours.
  • scale_colour_gradient() and scale_fill_gradient(): continuous gradients.
  • guides(): customize or remove guides and legends.

More detail: ggplot2 colours, labels and annotations and legends and axes.

Themes and facets

theme_minimal()
theme_classic()
theme_bw()
theme_light()

theme(
  plot.title = element_text(face = "bold"),
  legend.position = "bottom",
  panel.grid.minor = element_blank()
)

facet_wrap(~ class, ncol = 3)
facet_grid(drv ~ year)

Use a theme to style backgrounds, grid lines and text. Use facets to create a panel for each category or category combination. See themes and faceting.

Exporting plots

ggsave(
  filename = "my-plot.png",
  plot = p,
  width = 8,
  height = 5,
  units = "in",
  dpi = 300,
  bg = "white"
)

ggsave("my-plot.pdf", plot = p,
       width = 8, height = 5)

Use PNG for raster images and PDF or SVG when a vector graphic is preferable. Read the ggsave tutorial for dimensions, resolution and formats.

Complete example

library(ggplot2)
library(dplyr)

summary_data <- mpg |>
  group_by(class) |>
  summarise(mean_hwy = mean(hwy),
            .groups = "drop")

p <- ggplot(summary_data,
            aes(reorder(class, mean_hwy),
                mean_hwy)) +
  geom_col(fill = "steelblue") +
  coord_flip() +
  labs(
    title = "Average highway fuel economy",
    x = "Vehicle class",
    y = "Mean highway mpg"
  ) +
  theme_minimal()

p
ggsave("average-fuel-economy.png",
       plot = p, width = 8, height = 5,
       dpi = 300)

ggplot2 FAQ

What is the basic ggplot2 syntax?

Start with ggplot(data, aes(x, y)) and add a geom layer with +, such as geom_point() or geom_line().

How do I add colour to a ggplot?

Map a variable inside aes(colour = group) for data-driven colours, or set colour = "steelblue" outside aes() for one fixed colour.

How do I save a ggplot?

Use ggsave("plot.png", plot = p, width = 8, height = 5, dpi = 300), replacing p with your plot object.

Return to the complete ggplot2 tutorial to continue learning.