R: Add marginal density/histogram to ggplot2 scatterplots
ggMarginal
R Documentation
Add marginal density/histogram to ggplot2 scatterplots
Description
Create a ggplot2 scatterplot with marginal density plots (default) or
histograms, or add the marginal plots to an existing scatterplot.
Usage
ggMarginal(p, data, x, y, type = c("density", "histogram", "boxplot"),
margins = c("both", "x", "y"), size = 5, ..., xparams, yparams)
Arguments
p
A ggplot2 scatterplot to add marginal plots to. If p is
not provided, then all of data, x, and y must be
provided.
data
The data.frame to use for creating the marginal plots. Optional
if p is provided and the marginal plots are reflecting the same data.
x
The name of the variable along the x axis. Optional if p is
provided and the x aesthetic is set in the main plot.
y
The name of the variable along the y axis. Optional if p is
provided and the y aesthetic is set in the main plot.
type
What type of marginal plot to show. One of: [density, histogram, boxplot].
margins
Along which margins to show the plots. One of: [both, x, y].
size
Integer describing the relative size of the marginal plots
compared to the main plot. A size of 5 means that the main plot is 5x wider
and 5x taller than the marginal plots.
...
Extra parameters to pass to the marginal plots. Any parameter that
geom_line(), geom_histogram(), or geom_boxplot() accepts
can be used. For example, colour = "red" can be used for any marginal plot type,
and binwidth = 10 can be used for histograms.
xparams
List of extra parameters to use only for the marginal plot along
the x axis.
yparams
List of extra parameters to use only for the marginal plot along
the y axis.
Value
An object of class ggExtraPlot. This object can be printed to show the
plots or saved using any of the typical image-saving functions (for example, using
png() or pdf()).
Note
The grid and gtable packages are required for this
function.
Since the size parameter is used by ggMarginal, if you want
to pass a size to the marginal plots, you cannot
use the ... parameter. Instead, you must pass size to
both xparams and yparams. For example,
ggMarginal(p, size = 2) will change the size of the main vs marginal plot,
while ggMarginal(p, xparams = list(size=2), yparams = list(size=2))
will make the density plot outline thicker.