Learn R Programming

ggplot2

Overview

ggplot2 is a system for declaratively creating graphics, based on The Grammar of Graphics. You provide the data, tell ggplot2 how to map variables to aesthetics, what graphical primitives to use, and it takes care of the details.

Installation

# The easiest way to get ggplot2 is to install the whole tidyverse:
install.packages("tidyverse")

# Alternatively, install just ggplot2:
install.packages("ggplot2")

# Or the development version from GitHub:
# install.packages("pak")
pak::pak("tidyverse/ggplot2")

Cheatsheet

Usage

It’s hard to succinctly describe how ggplot2 works because it embodies a deep philosophy of visualisation. However, in most cases you start with ggplot(), supply a dataset and aesthetic mapping (with aes()). You then add on layers (like geom_point() or geom_histogram()), scales (like scale_colour_brewer()), faceting specifications (like facet_wrap()) and coordinate systems (like coord_flip()).

library(ggplot2)

ggplot(mpg, aes(displ, hwy, colour = class)) +
  geom_point()

Lifecycle

ggplot2 is now over 10 years old and is used by hundreds of thousands of people to make millions of plots. That means, by-and-large, ggplot2 itself changes relatively little. When we do make changes, they will be generally to add new functions or arguments rather than changing the behaviour of existing functions, and if we do make changes to existing behaviour we will do them for compelling reasons.

If you are looking for innovation, look to ggplot2’s rich ecosystem of extensions. See a community maintained list at https://exts.ggplot2.tidyverse.org/gallery/.

Learning ggplot2

If you are new to ggplot2 you are better off starting with a systematic introduction, rather than trying to learn from reading individual documentation pages. Currently, there are several good places to start:

  1. The Data Visualization and Communication chapters in R for Data Science. R for Data Science is designed to give you a comprehensive introduction to the tidyverse, and these two chapters will get you up to speed with the essentials of ggplot2 as quickly as possible.

  2. If you’d like to take an online course, try Data Visualization in R With ggplot2 by Kara Woo.

  3. If you’d like to follow a webinar, try Plotting Anything with ggplot2 by Thomas Lin Pedersen.

  4. If you want to dive into making common graphics as quickly as possible, I recommend The R Graphics Cookbook by Winston Chang. It provides a set of recipes to solve common graphics problems.

  5. If you’ve mastered the basics and want to learn more, read ggplot2: Elegant Graphics for Data Analysis. It describes the theoretical underpinnings of ggplot2 and shows you how all the pieces fit together. This book helps you understand the theory that underpins ggplot2, and will help you create new types of graphics specifically tailored to your needs.

  6. For articles about announcements and deep-dives you can visit the tidyverse blog.

Getting help

There are two main places to get help with ggplot2:

  1. The Posit Community (formerly RStudio Community) is a friendly place to ask any questions about ggplot2.

  2. Stack Overflow is a great source of answers to common ggplot2 questions. It is also a great place to get help, once you have created a reproducible example that illustrates your problem.

Copy Link

Version

Install

install.packages('ggplot2')

Monthly Downloads

2,169,083

Version

4.0.1

License

MIT + file LICENSE

Issues

Pull Requests

Stars

Forks

Maintainer

Thomas Lin Pedersen

Last Published

November 14th, 2025

Functions in ggplot2 (4.0.1)

absoluteGrob

Absolute grob
Layout

Layout
Layer-class

Layers
Guide

Guides
Stat

Stats
Scale

Scales
Facet

Facets
Position

Positions
Geom

Geoms
Coord

Coords
add_theme

Modify properties of an element in a theme object
aes_position

Position related aesthetics: x, y, xmin, xmax, ymin, ymax, xend, yend
aes_linetype_size_shape

Differentiation related aesthetics: linetype, size, shape
aes_group_order

Aesthetics: grouping
aes_auto

Automatic aesthetic mapping
aes_colour_fill_alpha

Colour related aesthetics: colour, fill, and alpha
aes_

Define aesthetic mappings programmatically
aes_eval

Control aesthetic evaluation
aes

Construct aesthetic mappings
aes_all

Given a character vector, create a set of identity mappings
autolayer

Create a ggplot layer appropriate to a particular data type
annotation_custom

Annotation: Custom grob
annotation_map

Annotation: a map
annotation_raster

Annotation: high-performance rectangular tiling
annotate

Create an annotation layer
annotation_borders

Create a layer of map borders
annotation_logticks

Annotation: log tick marks
automatic_plotting

Tailoring plots to particular data types
as.list.ggproto

Convert a ggproto object to a list
as_labeller

Coerce to labeller function
class_ggplot_built

The ggplot built class
autoplot

Create a complete ggplot appropriate to a particular data type
class_labels

The labels class
calc_element

Calculate the element properties, by inheriting properties from its parents
binned_scale

Binning scale constructor
bidirection

Utilities for working with bidirectional layers
benchplot

Benchmark plot creation time. Broken down into construct, build, render and draw times.
check_device

Check graphics device capabilities
class_ggplot

The ggplot class
class_definitions

Class definitions
coord_map

Map projections
coord_flip

Cartesian coordinates with x and y flipped
combine_vars

Take input data and define a mapping between faceting variables and ROW, COL and PANEL keys
coord_fixed

Cartesian coordinates with fixed "aspect ratio"
coord_munch

Munch coordinates data
continuous_scale

Continuous scale constructor
class_theme

The theme class
coord_cartesian

Cartesian coordinates
class_mapping

The mapping class
complete_theme

Complete a theme
diamonds

Prices of over 50,000 round cut diamonds
coord_transform

Transformed Cartesian coordinate system
margin

Theme elements
coord_polar

Polar coordinates
cut_interval

Discretise numeric data into categorical
draw_key

Key glyphs for legends
economics

US economic time series
element_grob

Generate grid grob from theme element
datetime_scale

Date/time scale constructor
discrete_scale

Discrete scale constructor
faithfuld

2d density estimate of Old Faithful data
facet_wrap

Wrap a 1d ribbon of panels into 2d
expansion

Generate expansion vector for scales
expand_limits

Expand the plot limits, using data
facet_grid

Lay out panels in a grid
facet_null

Facet specification: a single panel.
fortify-multcomp

Fortify methods for objects produced by multcomp
fill_alpha

Modify fill transparency
element_render

Render a specified theme element into a grob
find_panel

Find panels in a gtable
geom_blank

Draw nothing
fortify.lm

Supplement the data fitted to a linear model with model fit statistics.
geom_abline

Reference lines: horizontal, vertical, and diagonal
geom_contour

2D contours of a 3D surface
fortify

Fortify a model with data.
geom_boxplot

A box and whiskers plot (in the style of Tukey)
geom_bar

Bar charts
geom_bin_2d

Heatmap of 2d bin counts
fortify.map

Fortify method for map objects
fortify.sp

Fortify method for classes from the sp package.
geom_hex

Hexagonal heatmap of 2d bin counts
geom_map

Polygons from a reference map
geom_crossbar

Vertical intervals: lines, crossbars & errorbars
geom_freqpoly

Histograms and frequency polygons
geom_density_2d

Contours of a 2D density estimate
geom_function

Draw a function as a continuous curve
geom_density

Smoothed density estimates
geom_jitter

Jittered points
geom_dotplot

Dot plot
geom_count

Count overlapping points
geom_segment

Line segments and curves
geom_rug

Rug plots in the margins
geom_quantile

Quantile regression
geom_point

Points
geom_polygon

Polygons
geom_qq_line

A quantile-quantile plot
geom_spoke

Line segments parameterised by location, direction and distance
geom_ribbon

Ribbons and area plots
geom_path

Connect observations
geom_smooth

Smoothed conditional means
get_alt_text

Extract alt text from a plot
geom_label

Text
add_gg

Add components to a plot
geom_violin

Violin plot
get_theme

Get, set, and modify the active theme
geom_raster

Rectangles
get_geom_defaults

Resolve and get geom defaults
get_last_plot

Retrieve the last plot to be modified or created.
get_strip_labels

Accessing a plot's facet strip labels
get_guide_data

Extract tick information from guides
ggproto

Create a new ggproto object
ggplot_gtable

Build a plot with all the usual bits and pieces.
ggsave

Save a ggplot (or other grid object) with sensible defaults
ggplot2-package

ggplot2: Create Elegant Data Visualisations Using the Grammar of Graphics
ggplot_build

Build ggplot for rendering.
ggplot2-ggproto

Base ggproto classes for ggplot2
gg_dep

Give a deprecation error, warning, or message, depending on version number.
ggplotGrob

Generate a ggplot2 plot grob.
gg_par

Interpreter for graphical parameters
ggplot

Create a new ggplot
CoordSf

Visualise sf objects
ggtheme

Complete themes
guide_colourbar

Continuous colour bar guide
guide_axis

Axis guide
guide_axis_logticks

Axis with logarithmic tick marks
guide_bins

A binned version of guide_legend
guide_axis_stack

Stacked axis guides
guide_coloursteps

Discretized colourbar guide
guide_axis_theta

Angle axis guide
graphical-units

Graphical units
labeller

Construct labelling specification
label_bquote

Label with mathematical expressions
guides

Set guides for each scale
guide_none

Empty guide
hmisc

A selection of summary functions from Hmisc
guide_legend

Legend guide
guide_custom

Custom guides
is_rel

Reports whether x is a rel object
is_ggproto

Reports wether x is a type of object
ignoring_data

Ignoring and exposing data
luv_colours

colors() in Luv space
lims

Set scale limits
layer_geoms

Layer geometry display
labellers

Useful labeller functions
layer_positions

Layer position adjustments
labs

Modify axis, legend, and plot labels
layer_stats

Layer statistical transformations
layer_sf

Create a new sf layer that auto-maps geometry data
layer

Create a new layer
limits

Generate correct scale type for specified limits
mean_se

Calculate mean and standard error of the mean
max_height

Get the maximal width/length of a list of grobs
new_guide

Guide constructor
midwest

Midwest demographics
mpg

Fuel economy data from 1999 to 2008 for 38 popular models of cars
old_guide

The previous S3 guide system
map_data

Create a data frame of map data
merge_element

Merge a parent element into a child element
make_constructor

Produce boilerplate constructors
msleep

An updated and expanded version of the mammals sleep dataset
position_nudge

Nudge points a fixed distance
presidential

Terms of 12 presidents from Eisenhower to Trump
position_identity

Don't adjust position
print.ggproto

Format or print a ggproto object
position_dodge

Dodge overlapping objects side-to-side
position_jitterdodge

Simultaneously dodge and jitter
position_jitter

Jitter points to avoid overplotting
position_stack

Stack overlapping objects on top of each another
pattern_alpha

Modify transparency for patterns
print.ggplot

Explicitly draw plot
resolution

Compute the "resolution" of a numeric vector
qplot

Quick plot
render_strips

Render panel strips
scale_alpha

Alpha transparency scales
scale_binned

Positional scales for binning continuous data (x & y)
scale_colour_brewer

Sequential, diverging and qualitative colour scales from ColorBrewer
remove_missing

Convenience function to remove missing values from a data.frame
render_axes

Render panel axes
register_theme_elements

Define and register new theme elements
reexports

Objects exported from other packages
scale_identity

Use values without scaling
scale_colour_grey

Sequential grey colour scales
scale_colour_hue

Evenly spaced colours for discrete data
scale_colour_continuous

Continuous and binned colour scales
scale_date

Position scales for date/time data
scale_continuous

Position scales for continuous data (x & y)
scale_linetype

Scale for line patterns
scale_x_discrete

Position scales for discrete data
scale_colour_discrete

Discrete colour scales
scale_colour_gradient

Gradient colour scales
scale_linewidth

Scales for line width
scale_manual

Create your own discrete scale
scale_type

Determine default scale type
scale_colour_steps

Binned gradient colour scales
scale_colour_viridis_d

Viridis colour scales from viridisLite
sec_axis

Specify a secondary axis
set_last_plot

Set the last plot to be fetched by lastplot()
seals

Vector field of seal movements
scale_shape

Scales for shapes, aka glyphs
scale_size

Scales for area or radius
stat_summary_bin

Summarise y values at unique/binned x
stat_identity

Leave data as is
stat_manual

Manually compute transformations
sf_transform_xy

Transform spatial position data
stat_ellipse

Compute normal data ellipses
stat_connect

Connect observations
stat_ecdf

Compute empirical cumulative distribution
should_stop

Used in examples to illustrate when errors should occur.
stat_sf_coordinates

Extract coordinates from 'sf' objects
standardise_aes_names

Standardise aesthetic names
stat_unique

Remove duplicates
tidyeval

Tidy eval helpers
theme

Modify components of a theme
stat_summary_2d

Bin and summarise in 2d (rectangle & hexagons)
txhousing

Housing sales in TX
summarise_plot

Summarise built plot objects
update_geom_defaults

Modify geom/stat aesthetic defaults for future plots
translate_shape_string

Translating shape strings
waiver

A waiver object.
wrap_dims

Arrange 1d structure into a grid
subtheme

Shortcuts for theme settings
vars

Quote faceting variables
update_ggplot

Add custom objects to ggplot
transform_position

Convenience function to transform all position variables.
update_labels

Update axis/legend labels
zeroGrob

The zero grob draws nothing and has zero size.