Chapter 8 Faceting
In this chapter, we will introduce facets, which are usually used to combine continuous and categorical data.
8.1 Faceting on one variable
Facet partitions a plot into a matrix of panels. Each panel shows a different subset of the data. By default, facet_wrap
gives consistent scales, which is easier for comparison between different panels.
library(ggplot2)
mycol = "#7192E3"
ggplot(iris, aes(Sepal.Length, Sepal.Width)) +
geom_point(color = mycol) +
facet_wrap(~Species) +
theme_grey(18)
Rather than faceting on factor level, we can have one panel for each numerical variable.
library(pgmm)
library(dplyr)
library(tidyr)
data(wine)
tidywine <- wine %>%
pivot_longer(cols = -Type, names_to = "variable", values_to = "value")
tidywine %>%
ggplot(aes(value)) +
geom_histogram() +
facet_wrap(~variable) +
ggtitle("Consistent scales") +
theme_grey(14)
Axis scales can be made independent, by setting scales to free
, free_x
, or free_y
.
In this case, scales = "free_x"
is a better option because the distribution of each numerical variable is more obvious.