ggExtra (version 0.1.0)

ggMarginal: 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 = "density", margins = "both", size = 5,
  marginCol = "black", marginFill = "grey")

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].
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.
marginCol
The colour to use for the outline of the marginal density/histogram.
marginFill
The colour to use for the fill of the marginal histogram (not used when type is "density")

Value

  • An object of class ggExtraPlot. This extra class gets added onto a ggplot2 object in order for the print generic to easily work with this object. This means that the return value from this function can be printed or saved for later.

Examples

Run this code
if (requireNamespace("ggplot2", quietly = TRUE)) {
  if (requireNamespace("gridExtra", quietly = TRUE)) {
    if (requireNamespace("grid", quietly = TRUE)) {
      p <- ggplot2::ggplot(mtcars, ggplot2::aes(wt, mpg)) + ggplot2::geom_point()
      ggMarginal(p)

      set.seed(30)
      df <- data.frame(x = rnorm(500, 50, 10), y = runif(500, 0, 50))
      p2 <- ggplot2::ggplot(df, ggplot2::aes(x, y)) + ggplot2::geom_point()
      ggMarginal(p2)
      ggMarginal(p2, type = "histogram")
      ggMarginal(p2, margins = "x")
      ggMarginal(p2, size = 2)
      p2 <- p2 + ggplot2::ggtitle("Random data") + ggplot2::theme_bw(30)
      ggMarginal(p2)

      ggMarginal(data = df, x = "x", y = "y")

      set.seed(30)
      df2 <- data.frame(x = c(rnorm(250, 50, 10), rnorm(250, 100, 10)),
                        y = runif(500, 0, 50))
      p3 <- ggplot2::ggplot(df2, ggplot2::aes(x, y)) + ggplot2::geom_point()
      ggMarginal(p3)
    }
  }
}

Run the code above in your browser using DataLab