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.
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.
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:
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.
Categorical (or qualitative) variable: takes values that are not numerical (not numbers)
Numeric (or quantitative) variable: takes values that are numeric (numbers)
Discrete variable: A numeric variable whose possible values can be listed.
Continuous variable: A numeric variable who possible values are from interval of real numbers.
Exercise: Given an example of each data type (categorical, discrete and continuous).
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.
cty vs hwy
scatter plotggplot(data = mpg) +
geom_point(mapping = aes(x = cty, y = hwy))
ggplot()
creates a coordinate system that you can add
layers to.
ggplot()
is the data set to use in
the graph.geom_point()
adds a scatter plot (which is
called a layer) to the current plot.ggplot(data = mpg) +
geom_point(mapping = aes(x = cty, y = hwy))
geom_point()
function
mapping
argument: defines how variables in your data
set are mapped to visual properties.
aes()
x
and y
arguments of aes()
specify which variables to map to the x and y axes. You don’t have to
have quotation marks for variable names.data
argument,
in this case, mpg
.displ
vs hwy
from
the mpg
data set.ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy))
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
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")
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.
Create proper bar plots to answer the following questions:
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))
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.
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.
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
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))
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.
Create a multiple boxplot for variables manufacturer
and
cty
, answer the following question:
ggplot(data = <DATA>) +
<GEOM_FUNCTION>(mapping = aes(<MAPPINGS>))
This template contains the most basic information needed to create a graph:
<DATA>
.<GEOM_FUNCTION>
.<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
How are these two plots similar?
Both plots use the same data set, but different visual objects (which we call geoms).
# 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.
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()
In this class, we learned some basics of data visualization with
ggplot2
in R. You are required to
geom
functions.ggplot2