Ggplot2

Overview
Ggplot2 is the visualisation package of Tidyverse. It utilises the grammar of graphics (the gg in ggplot2) to create plots/figures in a layered/compartmentalised fashion.
There are multiple parts of a ggplot2 figure including:
- The ggplot2 object that contains the aesthetics
- The aesthetics: This is the data and what they are mapped to (x axis, y-axis, colour etc.)
- The geom layers: This is how the aesthetics are visualised (bar chart, boxplot, histogram etc.)
- The guides: The text and other information on the axes abd legends (labels, titles, etc.)
- Facetting: Splitting of data to multiple plots (e.g. side by side box plots displaying different metrics)
This website aims to quickly cover the most commonly used ggplot2
functions and uses. Therefore there are a lot more ggplot2
functions than those covered here. Please check the below link for the full list.
Sections
There are various sections for ggplot2
. These are summarised below.
Anatomy
Creating a basic plot with ggplot2
. In essence the introduction to ggplot2
usage.
- Basic plot: Creation of a basic plot with
ggplot2
- Input data: The required input format data for
ggplot2
.- Discusses the difference between tidy/long data and wide/messy data.
- Aesthetics: What they are, the different types, and their usage.
- Components: What components are and how to add (
+
) them to aggplot2
object.
Layers
Arguably the most important component for ggplot2
are the layers. Layers (also known as geom) are used to plot the data in different ways, i.e. different plots. This website will cover a few of the most commonly used ones.
geom_bar()
: Bar chart.geom_histogram()
: histogram.geom_line()
: Line graph.geom_point()
: Scatter plot.geom_boxplot()
: Box and whisker plot.- Other geoms: Other useful geom layers.
Output
How to save the output of ggplot2
objects.
ggsave()
: Save aggplot
object/figure to a static image file.pathcwork
: Combing multiplegpglot2
objects into the same graphic/image. (https://patchwork.data-imaginist.com/)ggplotly()
: Convert aggplot2
object to an interactive plotly object and save it as an HTML file.
Customisation
On top of layers there are various other components. These include:
- Labels: Modifying labels on the axes, legend, and other plot labels.
- Scale values: How to modify the scale of the x and y axis (e.g. plot values as log10 values or square root values)
- Colour scales: How to set the colours for aesthetics.
- Facetting: Creation of multiple of the same type of plot by subsetting the visualised data by one or two metadata categories.
- Abline: Adding a straight line to a plot and its corresponding y=mx+c equation.
- Coordinate systems: Modify how the x and y aesthetics combine.