A marginal plot is an extension of scatter plot which not only shows the relationship between two variables but also shows the individual distributions such as Histogram, Box plots of the variables.
In this recipe we are going to use ggplot2 as well as ggExtra package to plot the required Marginal plot. ggplot2 package is based on the book Grammar of Graphics by Wilkinson. This package provides flexibility while incorporating different themes and plot specification with a high level of abstraction. The package mainly uses aesthetic mapping and geometric objects as arguments. Different types of geometric objects include:
The basic syntax of gggplot2 plots is:
ggplot(data, mapping = aes(x =, y=)) + geometric object
ggExtra Package is mainly used to further enhance the built-in features of "ggplot2" by providing us with various functions to create Marginal plots especially Histogram and Boxplot.
This recipe demonstrates how to make a Marginal Plots using ggplot2 and ggExtra.
We will take an example of normal distribution along x and y axis and showcase the individual histogram and boxplot of the same.
# ggplot for data visualisation library(ggplot2) # installing ggExtra for marginal plots using devtools install.packages("ggExtra") library(ggExtra) # Creating a dataframe of normally distributed 1000 points with mean = 25 and std.dev = 5 norm_dist = data.frame(x = rnorm(1000, 25, 5), y = rnorm(1000, 25, 5)) norm_dist
x y 20.08595 27.34024 24.57561 33.94111 31.76342 33.02787 31.81128 15.18382 23.61155 31.49135 ... ... 24.98564 27.50006 25.33502 32.35901 26.72924 29.06489 23.44376 22.31388 20.21346 19.30083
We use geometric object as geom_point() to plot a scatter plot (x vs y)
scat_plot = ggplot(norm_dist, mapping = aes(x, y )) + geom_point() + labs(title = "X vs Y") scat_plot
We use "ggExtra::ggMarginal()" function to plot a marginal plot.
syntax: ggExtra::ggMarginal(x , type = )
# Marginal Histogram plot ggExtra::ggMarginal(scat_plot, type="histogram")
# Marginal Boxplot ggExtra::ggMarginal(scat_plot, type="boxplot")