10.3 Marginal plots

Function ggMarginal from package {ggExtra} allows to easily add histograms, boxplots or density plots to the margins of a scatter plot.

library(ggExtra)

# Save the classic plot to an object.
p <- ggplot(data=geneexp, mapping=aes(x=sample1, y=sample2)) +
      geom_point()
# add marginal histogram
ggMarginal(p, type="histogram")

# add marginal density
ggMarginal(p, type="density")

# add marginal boxplot
ggMarginal(p, type="boxplot")

The mapping of variables (for example, using color or fill) can also be inherited by the marginal plots.

# add mapping of points to "DE" column :
p <- ggplot(data=geneexp, mapping=aes(x=sample1, y=sample2, color=DE)) +
  geom_point()

# tell ggMarginal to color / split the boxplot according to variable mapped in color/colour
ggMarginal(p, type="boxplot", groupColour = TRUE)

Let’s add more features that we have learned in this workshop:

# add mapping of points to "DE" column :
p <- ggplot(data=geneexp, mapping=aes(x=sample1, y=sample2, color=DE)) +
  geom_point() +
  theme_minimal(base_size = 16) +
  geom_rug(alpha=0.4, sides = "tr") +
  geom_density_2d(alpha=0.2, colour = "pink") +
  ggtitle("Example of ggMarginal") +
  theme(legend.position="bottom", plot.title = element_text(hjust = 0.5))

# tell ggMarginal to color / split the boxplot according to variable mapped in color/colour
ggMarginal(p, type="boxplot", groupColour = TRUE)