R ggplot2

ggplot2 is a package for plotting and other data visualization tasks.


Installation

ggplot2 is a part of the tidyverse collection.


Usage

The core ggplot function returns a ggplot object. This object does nothing on its own; geometry functions must be applied by 'adding' to the object.

As a basic example:

library(tidyverse)

ggplot(data = df, mapping = aes(x = foo, y = bar)) + geom_point() + geom_smooth()

Geometry function include:

Aesthetic Mappings

The aes option creates an aesthetic mapping object. The main point of this function call is to standardize property names. For example, color, colour, col, and fg are all coerced to the same property name. The mapping option can be specified for either the ggplot function for global properties, or for a geometry function for local properties. Consider:

ggplot(data = df, mapping = aes(x = foo, y = bar)) + geom_point(aes(color="blue")) + geom_smooth(aes(color="red"))

The aes function can also evaluate functions of vectors, like:

aes(x = foo/bar, y = baz^2)

Note however that the function eagerly evaluates properties, so tricks have to be used if attempting to abstract the function call, as by a macro.


Theming

Themes are used to customize the appearance of a graph. They are applied to a ggplot object with the addition (+) operator.

library(tidyverse)
ggplot(data = DATA, mapping = aes(MAPPINGS)) +  GEOM_FUNC() + THEME_OBJ

Theme Objects

A set of default themes are built into the ggplot2 package and accessible from functions:

Alternatively, construct a new theme using the theme function.

ggplot(data = df, mapping = aes(x = foo, y = bar)) + mytheme

A common strategy is to use one of the above default themes as a starting point and then to apply customizations.

ggplot(data = df, mapping = aes(x = foo, y = bar)) + theme_minimal() + mytheme

Options

To set the font for a graph's text:

mytheme <- theme(text = element_text(family = "DejaVu"))

To enlarge the title:

mytheme <- theme(plot.title = element_text(size = 20))

Note that targetting title instead of plot.title would affect the size of all title-like objects (e.g. axes labels, legend title, and so on).

To rotate the x-axis labels 90 degrees:

mytheme <- theme(axis.text.x = element_text(angle = 90, hjust = 0.5, vjust = 0.5))

To color the y-axis labels:

mytheme <- theme(axis.text.y = element_text(colour = "grey20"))

To italicize the group titles in a faceted plot:

mytheme <- theme(strip.text = element_text(face = "italic"))


See also

ggplot2 package reference


CategoryRicottone

R/Ggplot2 (last edited 2026-09-03 14:32:12 by DominicRicottone)