Introduction to R

Data visualization in ggplot2

Yu Cheng Hsu

Learning objectives

By the end of this session, you will

  • Understand the basic grammar and layered structure of ggplot2
  • Identify common graph components and choose an appropriate chart type
  • Create simple plots using data, aesthetics, and geometric layers
  • Interpret the main elements of a ggplot2 figure

We DO NOT expect:

  • Memorize functions in the ggplot2

Package

  • A package is a bundle of functions, data, and documentation. You can import them through
library(package_name)
  • while using functions under the package you can use
package_name::function_name()

or

library(package_name)
function_name()
  • You can check what packages has been installed, imported to your environment using the tab Packages

Checking packages

Checking packages

Installing package

Golden rule: refers to the documentation of the specific package

  • CRAN (the Comprehensive R Archive Network) (Major package channel)
install.packages("ggplot2")
install.packages("tidyverse")
  • Bioconductor (Biomedical packages)
BiocManager::install("DESeq2")
  • Github (Codes at developmental stage)
devtools::install_github("tidyverse/ggplot2")

Introduction to ggplot2

About ggplot2

  • Visualization library in R for creating elegant and complex visualizations.
  • ggplot2 is part of the tidyverse collection of R packages.
  • Developed by Hadley Wickham (Wickham 2010). He received the COPSS Presidents’ Award for his contributions to the tidyverse collection.
  • Flexible and intuitive once you understand its core concepts.
library(ggplot2)

About the data

iris is a dataset introduced by Ronald Fisher in 1936 collect the iris flower morphology measurements from 3 species

  • Setosa,
  • Versicolor
  • Virginica

it measures the length and width of iris’s sepal and petal

data(iris)
head(iris)
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa

Iris flower

Iris flower

ggplot2 example

  • What are the elements in a graph ?

Components in the graph

Common components of a figure, figure from Wickham (2016)

Common components of a figure, figure from Wickham (2016)

Choosing the Visualization

Thinking process and decision flowchart will help you determine which type of graph to use (at least within the scope of this course):

  1. What is the purpose of displaying the graph?
  2. What types of data are you going to present?

flowchart LR
  A{Data type} -->|Continuous| B{Purpose}
  A{Data type}  -->|Discrete| C{Purpose}

  B{Purpose}-->|Exploration| D((Histogram/Boxpot))
  B{Purpose} -->|Association| E((Scatter plot))
  B{Purpose} -->|Association+time| T((Line plot))

  C{Purpose}-->|Exploration| F((Bar chart))
  C{Purpose} -->|Association| G((Tree map))

Overview of ggplot2 logics

ggplot2 desgined as you are plotting by hands, so the process will looks like

  1. Defining coordinate systems
  2. Plotting dots, lines, bars, and etc.
  3. Adding legend and axis informations

Layer features of ggplot2

Layer features of ggplot2

Layer 1: Coordinate system

First, we define the coordinate system for our iris data in R

The function is ggplot(), which takes two arguments 1

  • data: The data you are going to use
  • mapping: Should be wrapped in aes() specifying how each column maps to the coordinate.
# Initialize a ggplot object with 
# data and aesthetic mappings
p <- ggplot(data=iris, 
  mapping = aes(x = Sepal.Length))
p  # Display the base plot (no layers added yet)

# Alternative 
# p <- ggplot(iris, aes(Sepal.Length))
# p
Figure 1: Showing coordinate systems in ggplot2

Layer 2: Plotting data

The general format for plotting items will be

geom_XXX(mapping=aes())

In aes(), you can map anything to the figure, common terms could be

  • x
  • y
  • color, or colour
  • fill, shape, etc.

These functions are named in the format geom_XXXX:

Function name
Histogram geom_histogram()
Box chart geom_boxplot()
Bar chart geom_bar()
Scatter chart geom_point()
Line chart geom_line()

Layer 2: Example

p+geom_point(aes(y = Petal.Width, color=Species))

Scatter plot for Sepal length and Pedal width

Scatter plot for Sepal length and Pedal width
p+geom_boxplot()

Box plot for Sepal length

Box plot for Sepal length
  • + operator to stack on the original ggplot()
  • Adding additional mapping in the geom_XXX()
  • Overwriting mapping in the ggplot()

More examples

ggplot(data=iris)+
  geom_histogram(aes(x=Petal.Length, color=Species))

Histogram for Petal length

Histogram for Petal length
ggplot(data=iris)+
  geom_bar(aes(x=Species,fill=Species))

Histogram for Petal length

Histogram for Petal length

Some notes 1: color affects the border color (dots/lines), fill affects the rectangle color

Layer 3: Legends and axis

Scales are functions indicate how each variable behave and presents on the graph. The function usually in the format scale_(AES)_(datatype):

Discrete Continuous
X scale_x_discrete() scale_x_continuous()
Y scale_y_discrete() scale_y_continuous()
color scale_color_discrete() scale_color_continuous()

Most of time you only need to handle the presentation in Elements in the scale

Argument name Axis Legend
name Label Title
breaks Ticks Key
labels Tick label Key Label

Example

# Create a scatter plot with customized axis and color legend labels
   p +
  geom_point(aes(y = Petal.Width, color=Species)) +  # Add points layer for data representation
  scale_x_continuous(name="Sepal Length") +  # Customize x-axis label
  scale_y_continuous(name="Petal Width") + # Customize y-axis label
  scale_colour_discrete(name="Species name")  # Customize color legend title
Figure 2: Scatter plot of MPG vs cylinders with customized axis and legend labels.

Save figure

Add the function ggsave("FILE_PATH+FILE_NAME.png") after your ggplot instructions:

# Saving plots as figure_theme_grey.png at the folder figure
ggsave("figure_1.png",p)
  • It support most of the common image formats like pdf, jpeg, png

Saved figure location

Saved figure location

Final notes

  • There are far more things you can do in ggplot2
  • Try to look up on the reference (or even use AI) when you need it.

File structure

  • count_matrix.csv

RNA (In rows) expresion level for each sample (in column)

  • sample_metadata.csv

Information for each mouse

Loading/saving data from folders

  • By default, R sets the working directory to your Documents folder.
  • Use setwd(PATH/TO/NEW/WORKING/DIRECTORY) to change the working directory.
  • Use getwd() to see your current working directory.

Consider the following file structure

/ (root)
├── home
│   └── user
│       ├── documents
│       │   ├── course
│       │   │   ├── THIS_MARKDOWN.rmd
│       │   │   └── IMAGE.png
│       │   └── notes.txt
│       └── downloads
|           └── data.csv
└── var

There are two ways of specifying a path:

  1. Absolute path The full location of the file or directory.
  2. Relative path The location of the file or directory relative to the current directory.

Absolute Path

/ (root)
├── home
│   └── user
│       ├── documents
│       │   ├── course
│       │   │   ├── THIS_MARKDOWN.rmd
│       │   │   └── IMAGE.png
│       │   └── notes.txt
│       └── downloads
|           └── data.csv
└── var

Reminder for Windows system

  • You will find your file path using \ instead of / in your file explorer. In R, you need to transform these \s to / if you directly copy and paste the file path.
  • You need to indicate your drive so it usually looks like C:\Users\Ray\Blah\Blah

Absolute Path

An absolute path starts from the root directory (/) and specifies the full path to a file or directory.

  • Path to THIS_MARKDOWN.rmd: /home/user/documents/course /THIS_MARKDOWN.rmd
  • Path to data.csv: /home/user/downloads/data.csv

Relative path

/ (root)
├── home
│   └── user
│       ├── documents
│       │   ├── course
│       │   │   ├── THIS_MARKDOWN.rmd
│       │   │   └── IMAGE.png
│       │   └── notes.txt
│       └── downloads
|           └── data.csv
└── var

Relative Path

A relative path is defined relative to the current working directory.

  • ./ refer to the current directory,
  • ../ means “go up one directory level”.

Assume that we are working on THIS_MARKDOWN.rmd, so the current directory is /home/user/documents /course.

  • Path to IMAGE.png : ./IMAGE.png or IMAGE.png
  • Path to data.csv: ../../data.csv

Bibilography notes

Wickham, Hadley. 2010. “A Layered Grammar of Graphics.” Journal of Computational and Graphical Statistics 19 (1): 3–28.
———. 2016. Ggplot2: Elegant Graphics for Data Analysis. Springer-Verlag New York. https://ggplot2.tidyverse.org.