In this session, we will introduce how to visualize data using ggplot2. This lecture is based on UC Business Analytics R Programming Guide.
While we can use the built-in functions in the base package in R to create figures, the package ggplot2 creates advanced graphs with simple and flexible commands.
First, we load the necessary packages, check conflict functions, and get a glimpse of the dataset mpg from the R package ggplot2.
library(tidyverse)
library(conflicted)
conflict_prefer("lag", "dplyr")
conflict_prefer("filter", "dplyr")
glimpse(mpg)## Rows: 234
## Columns: 11
## $ manufacturer <chr> "audi", "audi", "audi", "audi", "audi", "audi", "audi", "…
## $ model <chr> "a4", "a4", "a4", "a4", "a4", "a4", "a4", "a4 quattro", "…
## $ displ <dbl> 1.8, 1.8, 2.0, 2.0, 2.8, 2.8, 3.1, 1.8, 1.8, 2.0, 2.0, 2.…
## $ year <int> 1999, 1999, 2008, 2008, 1999, 1999, 2008, 1999, 1999, 200…
## $ cyl <int> 4, 4, 4, 4, 6, 6, 6, 4, 4, 4, 4, 6, 6, 6, 6, 6, 6, 8, 8, …
## $ trans <chr> "auto(l5)", "manual(m5)", "manual(m6)", "auto(av)", "auto…
## $ drv <chr> "f", "f", "f", "f", "f", "f", "f", "4", "4", "4", "4", "4…
## $ cty <int> 18, 21, 20, 21, 16, 18, 18, 18, 16, 20, 19, 15, 17, 17, 1…
## $ hwy <int> 29, 29, 31, 30, 26, 26, 27, 26, 25, 28, 27, 25, 25, 25, 2…
## $ fl <chr> "p", "p", "p", "p", "p", "p", "p", "p", "p", "p", "p", "p…
## $ class <chr> "compact", "compact", "compact", "compact", "compact", "c…
Now we need to understand the data and each variable in the data. This dataset contains 38 popular models of cars from 1999 to 2008. (Fuel Economy Data).
The basic idea of creating plots using the R package ggplot2 is to specify each component of the following and combine them with +.
The ggplot() function plays an important role in data visualization as it is very flexible for plotting many different types of graphic displays.
The logic when using ggplot() function is: ggplot(data, mapping) + geom_function().
The following code chunk shows how we can obtain a scatter plot to study the relationship between engine displacement and highway mileage per gallon.
The aesthetic mappings allow to select variables to be plotted and use data properties to influence visual characteristics such as color, size, shape, position, etc. As a result, each visual characteristic can encode a different part of the data and be utilized to communicate information.
All aesthetics for a plot are specified in the aes() function call.
For example, we can add a mapping from the class of the cars to a color characteristic:
ggplot(mpg, aes(x = displ, y = hwy, color = class)) +
geom_point() + theme(text = element_text(size = 20))Note:
We should note that in the above code chunk, “class” is a variable in the data and therefore, the commend specifies a categorical variable is used as the third variable in the figure.
Using the aes() function will cause the visual channel to be based on the data specified in the argument. For example, using aes(color = “blue”) won’t cause the geometry’s color to be “blue”, but will instead cause the visual channel to be mapped from the vector c(“blue”) — as if we only had a single type of engine that happened to be called “red”.
Building on these basics, we can use ggplot2 to create almost any kind of plot we may want. These plots are declared using functions that follow from the Grammar of Graphics. ggplot2 supports a number of different types of geometric objects, including:
Each of these geometries will make use of the aesthetic mappings provided, albeit the visual qualities to which the data will be mapped will differ. For example, we can map data to the shape of a geom_point (e.g., if they should be circles or squares), or we can map data to the line-type of a geom_line (e.g., if it is solid or dotted), but not vice versa.
Almost all geoms require an x and y mapping at the bare minimum.
What makes this really powerful is that you can add multiple geometries to a plot, thus allowing you to create complex graphics showing multiple aspects of your data.
# plot with both points and smoothed line
ggplot(mpg, aes(x = displ, y = hwy)) +
geom_point() +
geom_smooth() +
theme(text = element_text(size = 20))Since the aesthetics for each geom can be different, we could show multiple lines on the same plot (or with different colors, styles, etc).
For example, we can plot both points and a smoothed line for the same x and y variable but specify unique colors within each geom:
ggplot(mpg, aes(x = displ, y = hwy)) +
geom_point(color = "blue") +
geom_smooth(color = "red") +
theme(text = element_text(size = 20))It is also possible to give each geom a different data argument, so that we can show multiple data sets in the same plot.
If we specify an aesthetic within ggplot(), it will be passed on to each geom that follows. Or we can specify certain aes within each geom, which allows us to only show certain characteristics for that specific layer (i.e. geom_point).
The following bar chart shows the frequency distribution of vehicle class. We can find that y axis was defined as the count of elements that have the particular type. This count is not part of the data set, but is instead a statistical transformation that the geom_bar automatically applies to the data. In particular, it applies the stat_count transformation.
ggplot2 supports many different statistical transformations. For example, the “identity” transformation will leave the data “as is”. We can specify which statistical transformation a geom uses by passing it as the stat argument. For example, consider our data already had the count as a variable:
## # A tibble: 7 × 2
## class n
## <chr> <int>
## 1 2seater 5
## 2 compact 47
## 3 midsize 41
## 4 minivan 11
## 5 pickup 33
## 6 subcompact 35
## 7 suv 62
We can use stat = “identity” within geom_bar to plot our bar height values to this variable. Also, note that we now include n for our y variable:
ggplot(class_count, aes(x = class, y = n)) +
geom_bar(stat = "identity") +
theme(text = element_text(size = 20))We can also call stat_ functions directly to add additional layers. For example, here we create a scatter plot of highway miles for each displacement value and then use stat_summary() to plot the mean highway miles at each displacement value.
ggplot(mpg, aes(displ, hwy)) +
geom_point(color = "grey") +
stat_summary(fun.y = "mean", geom = "line", size = 1, linetype = "dashed") +
theme(text = element_text(size = 20))In addition to a default statistical transformation, each geom also has a default position adjustment which specifies a set of “rules” as to how different components should be positioned relative to each other. This position is noticeable in geom_bar() if we map a different variable to the color visual characteristic.
# bar chart of class, colored by drive (front, rear, 4-wheel)
ggplot(mpg, aes(x = class, fill = drv)) +
geom_bar() +
theme(text = element_text(size = 20))The geom_bar() by default uses a position adjustment of “stack”, which makes each rectangle’s height proprotional to its value and stacks them on top of each other. We can use the position argument to specify what position adjustment rules to follow:
# position = "dodge": values next to each other
ggplot(mpg, aes(x = class, fill = drv)) +
geom_bar(position = "dodge") +
theme(text = element_text(size = 20))Note: We may need to check the documentation for each particular geom to learn more about its positioning adjustments.
Whenever we specify an aesthetic mapping, ggplot() uses a particular scale to determine the range of values that the data should map to. It automatically adds a scale for each mapping to the plot.
# color the data by engine type
ggplot(mpg, aes(x = displ, y = hwy, color = class)) +
geom_point() +
theme(text = element_text(size = 20))However, the sclae used in the figure could be changed if needed. Each scale can be represented by a function with the following name: scale_, followed by the name of the aesthetic property, followed by an _ and the name of the scale. A continuous scale will handle things like numeric data, whereas a discrete scale will handle things like colors.
# same as above, with explicit scales
ggplot(mpg, aes(x = displ, y = hwy, color = class)) + geom_point() +
scale_x_continuous() + scale_y_continuous() +
scale_colour_discrete() +
theme(text = element_text(size = 20))While the default scales will work fine, it is possible to explicitly add different scales to replace the defaults. For example, we can use a scale to change the direction of an axis:
# milage relationship, ordered in reverse
ggplot(mpg, aes(x = cty, y = hwy)) +
geom_point() +
scale_x_reverse() +
scale_y_reverse() +
theme(text = element_text(size = 20))Similarly, we can use scale_x_log10() and scale_x_sqrt() to transform the scale. We can use scales to format the axes as well.
ggplot(mpg, aes(x = class, fill = drv)) +
geom_bar(width=0.75, position = "fill") +
scale_y_continuous(breaks = seq(0, 1, by = .2),
labels = scales::percent) +
labs(y = "Percent") +
theme(text = element_text(size = 18))A common parameter to change is which set of colors to use in a plot. While you can use the default coloring, a more common option is to leverage the pre-defined palettes from colorbrewer.org. These color sets have been carefully designed to look good and to be viewable to people with certain forms of color blindness. We can leverage color brewer palletes by specifying the scale_color_brewer(), passing the pallete as an argument.
Similar to scales, coordinate systems are specified with functions that all start with coord_ and are added as a layer. There are a number of different possible coordinate systems to use, including:
We can use geom_bar() + coord_polar() to create a pie chart.
class_count$percent <- round(class_count$n/sum(class_count$n)*100,2)
# Create a basic bar
pie <- ggplot(class_count, aes(x = "", y = percent, fill = class)) +
geom_bar(stat = "identity", width = 1, color = "white")
# Convert to pie (polar coordinates) and add labels
pie <- pie + coord_polar("y", start = 0) +
geom_text(aes(label = paste0(percent, "%")),
fontface = "bold", color = "black",
position = position_stack(vjust = 0.5))
# Add color scale (hex colors)
pie <- pie + scale_fill_brewer(palette = "Oranges")
# Remove labels and change font size
pie <- pie + theme_void() +
theme(text = element_text(size = 20))
pieSome useful functions:
We can create a donut chart by having a hole inside of a pie chart.
The only difference between the pie chart code is that we set: x = 2 and xlim = c(0.5, 2.5) to create the hole inside the pie chart. Additionally, the argument width in the function geom_bar() is no longer needed.
# Create a basic bar
donut <- ggplot(class_count, aes(x = 2, y = percent, fill = class)) +
geom_bar(stat = "identity", color = "white")
# Convert to pie (polar coordinates) and add labels
donut <- donut + coord_polar("y", start = 0) +
geom_text(aes(label = paste0(percent, "%")),
fontface = "bold", color = "black",
position = position_stack(vjust = 0.5))
# Add color scale (hex colors)
donut <- donut + scale_fill_brewer(palette = "Oranges")
# Remove labels and change font size
donut <- donut + theme_void() +
theme(text = element_text(size = 20)) +
xlim(0.5, 2.5)
donutIf we want to divide the information into multiple subplots, facets are ways to go. It allows us to view a separate plot for each case in a categorical variable. We can construct a plot with multiple facets by using the facet_wrap(). This will produce a “row” of subplots, one for each categorical variable (the number of rows can be specified with an additional argument).
Note:
We can facet_grid() to facet the data by more than one categorical variable.
We use a tilde (~) in our facet functions. With facet_grid() the variable to the left of the tilde will be represented in the rows and the variable to the right will be represented across the columns.
ggplot(mpg, aes(x = displ, y = hwy)) +
geom_point() +
facet_grid(year ~ cyl) +
theme(text = element_text(size = 20))Textual annotations and labels (on the plot, axes, geometry, and legend) are crucial for understanding and presenting information.
We can add titles and axis labels to a chart using the labs() function (not labels, which is a different R function!).
ggplot(mpg, aes(x = displ, y = hwy, color = class)) +
geom_point() +
labs(title = "Fuel Efficiency by Engine Power",
subtitle = "Fuel economy data from 1999 and 2008 for 38 popular models of cars",
x = "Engine Displacement (liters)",
y = "Fuel Efficiency (miles per gallon)",
color = "Car Type") +
theme(text = element_text(size = 20))It is also possible to add labels into the plot itself (e.g., to label each point or line) by adding a new geom_text or geom_label to the plot; effectively, we are plotting an extra set of data which happen to be the variable names.
# a data table of each car that has best efficiency of its type
best_in_class <- mpg %>%
group_by(class) %>%
filter(row_number(desc(hwy)) == 1)
ggplot(mpg, aes(x = displ, y = hwy)) +
geom_point(aes(color = class)) +
geom_label(data = best_in_class, aes(label = model), alpha = 0.5) +
theme(text = element_text(size = 20))However, we can find that two labels overlap one-another in the top left part of the plot on the previous slide. We can use the geom_text_repel() from the ggrepel package to help position labels.
Whenever we want to customize titles, labels, fonts, background, grid lines, and legends, we can use themes.
ggplot(mpg, aes(x=displ, y=hwy)) + geom_point() +
labs(title = "Fuel Efficiency by Engine Power",
x = "Engine Displacement (Liters)",
y = "Fuel Efficiency (Miles per gallon)") +
theme(axis.text.x = element_text(size = 18),
axis.text.y = element_text(size = 18),
axis.title.x = element_text(size = 18),
axis.title.y = element_text(size = 18))Note:
We only list some key components here.
See Modify
Components of A Theme and Complete
Themes for more details about the use of theme.
You can utilize the following single character keyboard shortcuts to enable alternate display modes (Xie, Allaire, and Grolemund (2018)):
A: Switches show of current versus all slides (helpful for printing all pages)
B: Make fonts large
c: Show table of contents
S: Make fonts smaller