The goal of this tutorial is to learn how to create Density Ridgeline plots combining the ggplot and ggridges libraries. These plots partially overlap line plots to create the visual impression of a mountain range, so they can be quite useful for visualizing changes in distributions over time or space.
# First we load the libraries
library(ggplot2)
library(ggridges)
# In this tutorial we are going to use the iris dataset
data("iris")
iris <- as.data.frame(iris)
head(iris)
## Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1 5.1 3.5 1.4 0.2 setosa
## 2 4.9 3.0 1.4 0.2 setosa
## 3 4.7 3.2 1.3 0.2 setosa
## 4 4.6 3.1 1.5 0.2 setosa
## 5 5.0 3.6 1.4 0.2 setosa
## 6 5.4 3.9 1.7 0.4 setosa
# To create a Density Ridgeline plot, just use the geom_density_ridges() function
ggplot(iris, aes(x = Sepal.Length, y = Species)) + geom_density_ridges()
## Picking joint bandwidth of 0.181
# We can control the way the different densities overlap with the scale parameter.
# A setting of scale=1 means the tallest density curve just touches the baseline of the next higher one
ggplot(iris, aes(x = Sepal.Length, y = Species)) + geom_density_ridges(scale=1)
## Picking joint bandwidth of 0.181
# Setting scale values below 1 create a separation between the curves
ggplot(iris, aes(x = Sepal.Length, y = Species)) + geom_density_ridges(scale=0.8)
## Picking joint bandwidth of 0.181
# Whereas values larger larger than 1 create more overlap
ggplot(iris, aes(x = Sepal.Length, y = Species)) + geom_density_ridges(scale=5)
## Picking joint bandwidth of 0.181
# Variable to be plotted in the y-axis should be factors
# However, we can use numeric variables in the y-axis just specifying the grouping aesthetic
# create a modified dataset that represents species as a number
iris_num <- transform(iris, Species_num = as.numeric(Species))
ggplot(iris_num, aes(x = Sepal.Length, y = Species_num, group = Species_num)) + geom_density_ridges()
## Picking joint bandwidth of 0.181
In this tutorial we have learnt how to create Density Ridges plots using the ggridges library