The ggplot2 package allows the creation of elegant
graphics and plots. It is particularly useful in the analysis of
multidimensional and/or multiserial data and as an aid for data
mining.
Two basic features of the package:
data.frame or tibble,+
operator to the base object.The basic function with which we need to start creating each graphic
is ggplot(). Two most common arguments of this function
are:
aes() (aesthetics) function which is used
for the features mapping.However, just calling the ggplot() function, even with a
dataset and a mapping specified, will not produce any meaningful
effect.
library (ggplot2)
df1 <- data.frame (a = 1:10, b = (1:10) + runif (10,-2,2), c = rnorm (10, mean=1:10))
df1## a b c
## 1 1 0.379087 -0.4778485
## 2 2 2.167112 3.3919359
## 3 3 1.205155 2.8190549
## 4 4 2.325317 4.8296347
## 5 5 5.157458 3.7048531
## 6 6 7.211680 4.7635013
## 7 7 8.840510 6.3231367
## 8 8 9.441156 8.4213264
## 9 9 9.456594 8.3114941
## 10 10 9.312134 9.5021602
Only after adding the appropriate layer (in this case we want to draw
a scatter plot using geom_point() geometry) can we obtain a
graph.
The ggplot2 package is quite flexible. The same graph can be obtained using different operations.
ggplot (df1, aes (x = a, y = b)) + geom_point ()
ggplot (df1) + geom_point (aes (x = a, y = b))
ggplot () + geom_point (data = df1, aes (x = a, y = b))
ggplot (df1, aes (x = a)) + geom_point (aes(y = b))In addition, you can (and it is even quite recommended for the purity of the code) place the base layer in a variable and then add subsequent layers to it.
Each type of layer (called geometry) has variety of
parameters which allows you to customize its look. The most popular are
size, shape, color and
fill.
g <- ggplot(df1, aes(x = a))
g +
geom_point (aes (y = b), size = 4, shape = 22, color = "red") +
geom_point (aes (y = c), size = 3, shape = 21, fill = "blue")A layer with lines instead of points is obtained by using
geom_line() geometry which is controlled by the parameters
linewidth and linetype.
g +
geom_point (aes (y = b), size = 4, shape = 22, color = "red", fill = "blue") +
geom_line (aes (y = c), linewidth = 1.2, linetype = 3, color = "darkgreen")The ggplot2 package also allows you to fit a linear
model to a series by using the geom_smooth() layer.
g +
geom_smooth (aes (y = b), method = "lm", linewidth = 1.2, color = "red") +
geom_point (aes (y = b), shape = 21, size = 3, fill = "black")Using the alpha parameter one can adjust the
transparency of some layers. This is especially useful when dealing with
a large amount of data points which overlap.
df.norm <- data.frame (x = rnorm (1e4, 0, 1), y = rnorm (1e4, 0, 1))
g.norm <- ggplot (df.norm, aes (x = x, y = y))
# No transparency
g.norm + geom_point (shape = 21)df.norm2 <- data.frame (x = rnorm (1e4,2,1), y = rnorm( 1e4,-2,1))
df.norm3 <- data.frame (x = rnorm (1e4,-2,1), y = rnorm (1e4,-2,1))
# No transparency
g.norm +
geom_point (shape=21, fill="blue", colour="blue") +
geom_point (data = df.norm2, shape=21, fill = "green", colour = "green") +
geom_point (data = df.norm3, shape=21, fill = "red", colour = "red")# 90% of transparency
g.norm +
geom_point (shape=21, fill = "blue", colour = "blue", alpha = 0.1) +
geom_point (data = df.norm2, shape = 21, fill = "green", colour = "green", alpha = 0.1) +
geom_point (data = df.norm3, shape = 21,fill = "red", colour = "red", alpha = 0.1)In addition to the graphic parameters relating to specific layers, it
is also possible to modify the properties of the entire plot using the
theme() function.
g +
geom_smooth (aes (y = b), method = "lm", linewidth = 1.2, color = "red") +
geom_point (aes (y = b), shape = 21, size = 3, fill = "black") +
theme (axis.title = element_text (size = 14),
axis.text = element_text (size = 14))There are many predefined themes, e.g. theme_bw(),
theme_minimal() or theme_classic(), which can
be used as a first choice for plotting neat figures.
g +
geom_smooth (aes (y = b), method = "lm", linewidth = 1.2, color = "red") +
geom_point (aes (y = b), shape = 21, size = 3, fill = "black") +
theme_bw ()g +
geom_smooth (aes (y = b), method = "lm", linewidth = 1.2, color = "red") +
geom_point (aes (y = b), shape = 21, size = 3, fill = "black") +
theme_minimal ()g +
geom_smooth (aes (y = b), method = "lm", linewidth = 1.2, color = "red") +
geom_point (aes (y = b), shape = 21, size = 3, fill = "black") +
theme_classic ()The predefined styles can by further modified by combining them with
the theme() function.
my_theme <- theme_dark() + theme (axis.title = element_text (size = 14),
axis.text = element_text (size = 14))
g +
geom_smooth (aes (y = b), method = "lm", linewidth = 1.2, color = "red") +
geom_point (aes(y = b), shape = 21, size = 3, fill = "black") +
my_themeAlthough the ggplot2 package can be used to plot data
stored in wide tables, it works much better with long tables (tidy
data). Placing the series one under the other instead of one next
to the other and adding a character or factor
column with the series label allows automatic series recognition and
legend generation, called grouping. To do this, proper mapping
should be done inside the aes() function.
library(dplyr)
library (tidyr)
# Pivot df1 from wide table to long table and add a new column
df1 %>%
pivot_longer (cols = 2:3, names_to = "ser") %>%
mutate (n = sample (20)) -> df2
df2## # A tibble: 20 × 4
## a ser value n
## <int> <chr> <dbl> <int>
## 1 1 b 0.379 12
## 2 1 c -0.478 16
## 3 2 b 2.17 8
## 4 2 c 3.39 13
## 5 3 b 1.21 10
## 6 3 c 2.82 6
## 7 4 b 2.33 18
## 8 4 c 4.83 1
## 9 5 b 5.16 11
## 10 5 c 3.70 7
## 11 6 b 7.21 4
## 12 6 c 4.76 14
## 13 7 b 8.84 3
## 14 7 c 6.32 19
## 15 8 b 9.44 17
## 16 8 c 8.42 9
## 17 9 b 9.46 15
## 18 9 c 8.31 20
## 19 10 b 9.31 2
## 20 10 c 9.50 5
Size mapping is also beneficial, for example, if we want to visualize the number of observations entering a given point.
To perform grouping in geom_smooth geometry, assign a
column name to the group parameter inside the
aes() function.
# Data generation
df3 <- data.frame (x = c (0:10, 5:15, 10:20),
y = c (0:10 + runif(11,-2,2), 5:15 + runif(11,-3,3), 10:20 + runif(11,-2,2)),
ser = rep (c ("R1","R2","R3"), each = 11))
g3 <- ggplot (df3, aes (x = x, y = y))
p <- geom_point (aes (fill = ser), size = 3, shape = 21)
# Without linear fit
g3 + pThe colors for individual series are selected automatically, but there is nothing stopping you from choosing them yourself.
g3 + p +
geom_smooth (aes (color = ser), method = "lm") +
scale_fill_manual (values = c ("red", "orange", "gold")) +
scale_color_manual (values = c ("red", "orange", "gold"))Another important type of plot is the histogram. The layer
geom_histogram() displays the counts (or density) with
bars, while geom_freqpoly() shows the empirical
distributions with lines. Let’s start with generating some random series
from normal distributions.
# Data generation
sizes <- c( 1e2, 1e3, 1e4)
sigmas <- c (0.5, 1)
mu <- 0
x1 <- rnorm (sizes[1], mu, sigmas[1])
x2 <- rnorm (sizes[2], mu, sigmas[1])
x3 <- rnorm (sizes[3], mu, sigmas[1])
x4 <- rnorm (sizes[1], mu, sigmas[2])
x5 <- rnorm (sizes[2], mu, sigmas[2])
x6 <- rnorm (sizes[3], mu, sigmas[2])
df.norm <- data.frame (x = c(x1, x2, x3, x4, x5, x6),
size = rep (sizes, sizes) %>% as.factor(),
sigma = rep (sigmas, each = sum (sizes)) %>% as.factor())
df.norm %>% filter (size == as.character (sizes[3])) %>% ggplot () -> gh
gh + geom_histogram (aes (x = x, fill = sigma, color = sigma))Using the position parameter you can control the
positioning of several histograms relative to each other. The default
value (stack) stacks one bar on top of the other,
fill normalizes the sum to one, and dodge
displays the bars side by side.
The identity option obscures one series from another, so
using transparency is useful.
To show the probability density instead of the number of counts, use
the after_stat (density) function. If we also need to plot
a certain function (e.g. probability density of the normal
distribution), for the entire x-axis range, we use the
stat_function() function. We provide the name of the
function (fun=...) and its parameters using a list
(args = list(...)).
gh +
geom_histogram (aes (x = x, y = after_stat (density), fill = sigma, colour = sigma),
position="identity", alpha = 0.3) +
stat_function (fun = dnorm, args = list (mean = 0, sd = 0.5))In the case of a larger number of series that can be grouped
according to one or more features, it is convenient to use the faceting
mechanism using the facet_grid() or
facet_wrap() functions.
ggplot (df.norm) +
geom_histogram (aes (x = x, y = after_stat (density), fill = size, colour = size), alpha = 0.6) +
facet_grid (size ~ sigma)Plots made using the ggplot2 package are saved to the
file in a different way than in the case of the basic
graphics package. The ggsave (filename)
function is used for this purpose, the basic argument of which is the
string storing the file name, and the additional parameters include:
plot - specifies which plot should be saved (default
plot = last_plot()),device - specifies the format in which the file is to
be saved (e.g. “png”, “eps”, “pdf”),width, height, units,
dpi - image parameters such as height, width, unit in which
the height and width are expressed, and resolution.