Learn R Programming

⚠️There's a newer version (3.5.0) of this package.Take me there.

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 the development version from GitHub:
# install.packages("devtools")
devtools::install_github("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 http://www.ggplot2-exts.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 three good places to start:

  1. The data visualisation and graphics for 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 you get up to speed with the essentials of ggplot2 as quickly as possible.

  2. If you’d like to take an interactive online course, try Data visualisation with ggplot2 by Rick Scavetta on datacamp.

  3. 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. A 2nd edition is due out in 2017.

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 graphic specifically tailored to your needs. The book is not available for free, but you can find the complete source for the book at https://github.com/hadley/ggplot2-book.

Getting help

There are two main places to get help with ggplot2:

  1. The 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

1,879,771

Version

3.0.0

License

GPL-2 | file LICENSE

Issues

Pull Requests

Stars

Forks

Maintainer

Last Published

February 23rd, 2024

Functions in ggplot2 (3.0.0)

cut_interval

Discretise numeric data into categorical
geom_boxplot

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

2d contours of a 3d surface
coord_cartesian

Cartesian coordinates
coord_fixed

Cartesian coordinates with fixed "aspect ratio"
geom_errorbarh

Horizontal error bars
fortify

Fortify a model with data.
aes_linetype_size_shape

Differentiation related aesthetics: linetype, size, shape
guide_legend

Legend guide
ggplot_build

Build ggplot for rendering.
geom_hex

Hexagonal heatmap of 2d bin counts
graphical-units

Graphical units
geom_smooth

Smoothed conditional means
geom_density

Smoothed density estimates
guide_colourbar

Continuous colour bar guide
geom_spoke

Line segments parameterised by location, direction and distance
ggplot_gtable

Build a plot with all the usual bits and pieces.
guide-exts

S3 generics for guides.
is.ggplot

Reports whether x is a ggplot object
fortify.lm

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

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

Theme elements
is.rel

Reports whether x is a rel object
aes_position

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

Create a new layer
element_grob

Generate grid grob from theme element
find_panel

Find panels in a gtable
mean_se

Calculate mean and standard error
annotation_raster

Annotation: high-performance rectangular tiling
annotation_logticks

Annotation: log tick marks
limits

Generate correct scale type for specified limits
fortify-multcomp

Fortify methods for objects produced by multcomp
as.list.ggproto

Convert a ggproto object to a list
borders

Create a layer of map borders
calc_element

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

Polygons
facet_grid

Lay out panels in a grid
merge_element

Merge a parent element into a child element
position_jitterdodge

Simultaneously dodge and jitter
geom_qq_line

A quantile-quantile plot
annotation_map

Annotation: a maps
position_nudge

Nudge points a fixed distance
coord_munch

Munch coordinates data
stat_summary_bin

Summarise y values at unique/binned x
midwest

Midwest demographics
scale_size

Scales for area or radius
scale_shape

Scales for shapes, aka glyphs
combine_vars

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

Leave data as is
geom_bin2d

Heatmap of 2d bin counts
theme

Modify components of a theme
facet_null

Facet specification: a single panel.
coord_polar

Polar coordinates
geom_rug

Rug plots in the margins
geom_blank

Draw nothing
geom_segment

Line segments and curves
continuous_scale

Continuous scale constructor.
expand_limits

Expand the plot limits, using data
mpg

Fuel economy data from 1999 and 2008 for 38 popular models of car
position_identity

Don't adjust position
gg_dep

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

Generate expansion vector for scales.
ggplot

Create a new ggplot
position_jitter

Jitter points to avoid overplotting
theme_get

Get, set, and modify the active theme
geom_freqpoly

Histograms and frequency polygons
geom_jitter

Jittered points
diamonds

Prices of 50,000 round cut diamonds
geom_raster

Rectangles
discrete_scale

Discrete scale constructor.
fortify.map

Fortify method for map objects
geom_label

Text
ggplot2-ggproto

Base ggproto classes for ggplot2
facet_wrap

Wrap a 1d ribbon of panels into 2d
is.Coord

Is this object a coordinate system?
faithfuld

2d density estimate of Old Faithful data
fortify.sp

Fortify method for classes from the sp package.
geom_abline

Reference lines: horizontal, vertical, and diagonal
geom_bar

Bar charts
geom_crossbar

Vertical intervals: lines, crossbars & errorbars
render_strips

Render panel strips
ggplot2-package

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

Contours of a 2d density estimate
geom_map

Polygons from a reference map
labs

Modify axis, legend, and plot labels
is.facet

Is this object a faceting specification?
resolution

Compute the "resolution" of a numeric vector
last_plot

Retrieve the last plot to be modified or created.
geom_violin

Violin plot
tidyeval

Tidy eval helpers
guides

Set guides for each scale
+.gg

Add components to a plot
ggplotGrob

Generate a ggplot2 plot grob.
hmisc

A selection of summary functions from Hmisc
geom_dotplot

Dot plot
geom_path

Connect observations
labellers

Useful labeller functions
labeller

Construct labelling specification
map_data

Create a data frame of map data
print.ggplot

Explicitly draw plot
max_height

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

Quantile regression
ggplot_add

Add custom objects to ggplot
geom_point

Points
geom_ribbon

Ribbons and area plots
transform_position

Convenience function to transform all position variables.
ggtheme

Complete themes
ggsf

Visualise sf objects
msleep

An updated and expanded version of the mammals sleep dataset
scale_date

Position scales for date/time data
scale_x_discrete

Position scales for discrete data
scale_linetype

Scale for line patterns
print.ggproto

Format or print a ggproto object
scale_colour_continuous

Continuous colour scales
scale_continuous

Position scales for continuous data (x & y)
ggproto

Create a new ggproto object
position_dodge

Dodge overlapping objects side-to-side
qplot

Quick plot
remove_missing

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

Objects exported from other packages
render_axes

Render panel axes
scale_type

Determine default scale type
scale_colour_gradient

Gradient colour scales
scale_manual

Create your own discrete scale
ggsave

Save a ggplot (or other grid object) with sensible defaults
is.theme

Reports whether x is a theme object
label_bquote

Label with mathematical expressions
stat_ellipse

Compute normal confidence ellipses
scale_colour_grey

Sequential grey colour scales
stat_function

Compute function for each x value
set_last_plot

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

Set scale limits
scale_colour_viridis_d

Viridis colour scales from viridisLite
should_stop

Used in examples to illustrate when errors should occur.
translate_qplot_ggplot

Translating between qplot and ggplot
stat_summary_2d

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

Translating between qplot and lattice
luv_colours

colors() in Luv space
position_stack

Stack overlapping objects on top of each another
stat_unique

Remove duplicates
presidential

Terms of 11 presidents from Eisenhower to Obama
txhousing

Housing sales in TX
stat

Calculated aesthetics
update_labels

Update axis/legend labels
vars

Quote faceting variables
scale_alpha

Alpha transparency scales
stat_ecdf

Compute empirical cumulative distribution
summarise_plot

Summarise built plot objects
scale_colour_brewer

Sequential, diverging and qualitative colour scales from colorbrewer.org
update_geom_defaults

Modify geom/stat aesthetic defaults for future plots
summary.ggplot

Displays a useful description of a ggplot object
scale_colour_hue

Evenly spaced colours for discrete data
waiver

A waiver object.
scale_identity

Use values without scaling
wrap_dims

Arrange 1d structure into a grid
seals

Vector field of seal movements
sec_axis

Specify a secondary axis
zeroGrob

The zero grob draws nothing and has zero size.
aes_colour_fill_alpha

Colour related aesthetics: colour, fill and alpha
aes_group_order

Aesthetics: grouping
absoluteGrob

Absolute grob
aes_auto

Automatic aesthetic mapping
aes_all

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

Construct aesthetic mappings
as_labeller

Coerce to labeller function
add_theme

Modify properties of an element in a theme object
aes_

Define aesthetic mappings programatically
annotation_custom

Annotation: Custom grob
autoplot

Create a complete ggplot appropriate to a particular data type
autolayer

Create a ggplot layer appropriate to a particular data type
annotate

Create an annotation layer
coord_flip

Cartesian coordinates with x and y flipped
draw_key

Key drawing functions
economics

US economic time series
coord_map

Map projections
geom_count

Count overlapping points
coord_trans

Transformed Cartesian coordinate system