Introduction

In this class, we will start to learn how to visualize data with the ggplot2 package in R. Again, to activate all functions in ggplot2, we need load the package. Usually we simply load tidyverse which contains ggplot2.

library(tidyverse)
## ── Attaching packages ──────────────────────── tidyverse 1.3.2 ──
## ✔ ggplot2 3.4.0      ✔ purrr   1.0.0 
## ✔ tibble  3.1.8      ✔ dplyr   1.0.10
## ✔ tidyr   1.2.1      ✔ stringr 1.5.0 
## ✔ readr   2.1.3      ✔ forcats 0.5.2

As we see, ggplot2 is part of the tidyverse package.


Warmup Exercise

Again, let’s use the fuel economy data mpg as the first data set to work on. To recall what we learned from last class, answer the following questions using R.

  1. How to have a quick view of data?
  2. How many samples are there in the data set? How many variables are there?
  3. What is the data type for the variable “model”? How about “cyl”? How about “displ”?
  4. What is the meaning of the variable “fl”?
  5. How to obtain the data from one variable, such as “drv”, and store it separately as a vector in R?


Introduction to data plots

Before we start to plot graphs, we need to review the basic knowledge of data plotting types. There are many types of them, and as below are a few examples, including some most commonly used ones:


Plot types depend on data types

Why do we have this many plot types? One reason is that we need different plots to best illustrate the relationship between (usually one or two) variables of different types.


Recall: variable types

Exercise: Given an example of each data type (categorical, discrete and continuous).


Create scatter plots in R

Now let’s learn from creating scatter plots, which is one of the most commonly used graphs in scientific research. Let’s plot the cty variable against the hwy variable in the mpg data set, which is given below.


The R Code for cty vs hwy scatter plot

ggplot(data = mpg) +
  geom_point(mapping = aes(x = cty, y = hwy))
ggplot(data = mpg) +
  geom_point(mapping = aes(x = cty, y = hwy))


Lab Exercise

  1. Make a scatter plot of displ vs hwy from the mpg data set.
  2. Observe the plot, what preliminary conclusion can you draw from the plot?
  3. Explain why the total number of data points on the plot is less than the total number of samples (which is 234).


Solution plot

ggplot(data = mpg) + 
  geom_point(mapping = aes(x = displ, y = hwy))


Overplotting

The reason why we see fewer points than the amount of samples is that, the values of displ and hwy are rounded so some points overlap with each other. This problem is known as overplotting.

For example, the fifth and the sixth sample share the same displ and hwy values.

mpg[5:6, c('displ', 'hwy')]  # This code shows the values from "hwy" and "displ" for the 5th and 6th sample
## # A tibble: 2 × 2
##   displ   hwy
##   <dbl> <int>
## 1   2.8    26
## 2   2.8    26


“jitter” positioning to avoid overplotting

We can add the option position = "jitter" into the geom_point function to avoid overplotting problem. By doing this, we add a small amount of random noise to each point, which spreads the points out.

ggplot(data = mpg) + 
  geom_point(mapping = aes(x = displ, y = hwy), position = "jitter")

Here the position argument controls position adjustments, which determines how to arrange geoms that would otherwise occupy the same space.


ggplot(data = mpg) + 
  geom_point(mapping = aes(x = displ, y = hwy), position = "jitter")


Create a bar plot

Next, let’s learn how to create a bar plot for one variable with ggplot2. The code template is very similar to that for scatter plots. But it must be for a categorical variable and we don’t need the y variable in the mapping. Now let’s plot the bar plot for the variable drv in the mpg data set.

ggplot(data = mpg) + 
  geom_bar(mapping = aes(x = drv))

Here we use the function geom_bar to create a bar plot.


ggplot(data = mpg) + 
  geom_bar(mapping = aes(x = drv))

A bar plot summarizes the count (or frequency) of each category in the data set.


Lab Exercise

Create proper bar plots to answer the following questions:

  1. Which vehicle class contains least samples in the data set?
  2. which three manufacturer contains most samples in the data set?


Create a colored bar plot

We can use the fill argument in the aes function to make a bar plot colored.

ggplot(data = mpg) + 
  geom_bar(mapping = aes(x = drv, fill = drv))


Here we use the same value of fill and x argument, which means “filled by colors of different x values”. If we use different values, it becomes a stacked bar plot.

ggplot(data = mpg) + 
  geom_bar(mapping = aes(x = drv, fill = class))


Stacked bar plot

A stacked bar plot is used to show the distribution among combination of two categorical variables by breaking down each bar into smaller colored bars. Observe the graph on the last page and answer the following questions.

  1. Is most SUV 4-wheel drive (4WD), forward-wheel drive (FWD), or rear-wheel drive (RWD)?
  2. Which is the most common drive train type for compact cars?
  3. What is the drive train type of 2seaters?
  4. What is the drive train type of pickups?


Box plots

Next, let’s learn how to create a box plot. A box plot summarizes key information about the center, spread and potential outliers of a numeric variable.

First, let’s review how to read a box plot.


Create a box plot

We use the function geom_boxplot to create a box plot.

ggplot(data = mpg) + 
  geom_boxplot(mapping = aes(x = displ))


ggplot(data = mpg) + 
  geom_boxplot(mapping = aes(y = displ)) # The plot can also be vertical


Create multiple boxplots

More often, multiple boxplots are used to compare the effect of a categorical variable on a numeric variable. It’s very easy to do this with ggplot. We simply use both x and y arguments.

For example, we hope to study the effect of drive train types on fuel economy measured by hwy. We can create the plots with the following code.

ggplot(data = mpg) +
  geom_boxplot(mapping = aes(x = drv, y = hwy))


ggplot(data = mpg) +
  geom_boxplot(mapping = aes(x = drv, y = hwy))


Make the graph look better

The graph above may not look very nice. We can manage many details to make it look better. We will save those details in future classes now but here I give you an example.


Lab Exercise

Create a multiple boxplot for variables manufacturer and cty, answer the following question:

  1. Within the data set, cars from which manufacturer is most fuel economic?
  2. Within the data set, cars from which manufacturer is least fuel economic?
  3. Do you think the conclusion from Q1 and Q2 is generally true for all cars from manufacturers?


Graphing template

ggplot(data = <DATA>) + 
  <GEOM_FUNCTION>(mapping = aes(<MAPPINGS>))

This template contains the most basic information needed to create a graph:

  1. We need a data set as <DATA>.
  2. We need to know which type of graph to create by selecting different <GEOM_FUNCTION>.
  3. We need to know which variables are used from <MAPPINGS>.

We will expand this template to more complicated cases in future classes. More details can be found at

https://github.com/rstudio/cheatsheets/blob/main/data-visualization.pdf


Creating a line graph

How are these two plots similar?

Both plots use the same data set, but different visual objects (which we call geoms).


Codes for a smooth line graph

# left
ggplot(data = mpg) + 
  geom_point(mapping = aes(x = displ, y = hwy))   # point geom

# right
ggplot(data = mpg) + 
  geom_smooth(mapping = aes(x = displ, y = hwy))  # smooth geom

The function geom_smooth creates a smoothed conditional means curve to fit the data. The shaded region represents the 95% (can be adjusted) confidence interval.

In this plot, there is statistical modeling behind it. Therefore we must learn statistical methods to fully understand the details.


Multiple-layer plot

What if we hope to combine the two plots into one plot? It is very simple to do it with ggplot2 - we just apply two geom functions which add two layers to the same plot.

    ggplot(data = mpg) + 
      geom_point(mapping = aes(x = displ, y = hwy)) + 
      geom_smooth(mapping = aes(x = displ, y = hwy))


We can put mapping into the ggplot function to avoid redundant codes

    ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) + 
      geom_point() + geom_smooth()


Summary

In this class, we learned some basics of data visualization with ggplot2 in R. You are required to

  1. understand which plot type to use for various types of variables
  2. understand how to create scatter plots, bar plots, box plots, multiple box plots and smoothed line graph with different geom functions.
  3. understand the basic template of plotting graphs with ggplot2
  4. make relevant plots to answer simple questions regarding a given data set