Ggplot2
Overview
Ggplot2 is the visualisation package of Tidyverse. It utilises the __grammar of graphics__ (the gg inggplot2`) to create plots/figures in a layered/compartmentalised fashion.
There are multiple parts of a ggplot2 figure including:
- The
ggplot2object 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 and 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. 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
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 aggplot2object
Layers
Arguably the most important component for ggplot2 are the layers. Layers (also known as geoms) 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 chartgeom_histogram(): Histogramgeom_line(): Line graphgeom_point(): Scatter plotgeom_boxplot(): Box and whisker plot- Other geoms: Other useful geom layers
Output
How to save the output of ggplot2 objects.
ggsave(): Save aggplotobject/figure to a static image filepatchwork: Combing multiplegglot2objects into the same graphic/imageggplotly(): Convert aggplot2object 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 labelstheme(): 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
- Includes how to create a statistical lm abline with the equation on the plot
- 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