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)

ggplot2 homepage

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.

Full ggplot2 reference page

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 a ggplot2 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.

Output

How to save the output of ggplot2 objects.

  • ggsave(): Save a ggplot object/figure to a static image file.
  • pathcwork: Combing multiple gpglot2 objects into the same graphic/image. (https://patchwork.data-imaginist.com/)
  • ggplotly(): Convert a ggplot2 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:

  • labs(): Modifying labels on the axes, legend, and other plot labels.
  • theme(): Modifying components of a theme including the legend position and the font sizes in the plot.
  • 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.
  • Guides: Modify the appearance of guides including the layout of the legend and axes values.
    • Setting number of rows for legend values
    • Allowing axis value/guides to dodge each other when they would otherwise overlap
  • Annotations: Adding text and lines onto the plotting area.
  • Coordinate systems: Modify how the x and y aesthetics combine.
    • Modify the x and y aspect ratio.
  • Facetting: Splitting a plot into multiple panels by subsetting the visualised data by one or two metadata categories.