- R Data Visualization Recipes
- Vitor Bianchi Lanzetta
- 56字
- 2021-07-02 23:33:29
How to do it...
- Draw the center plot using ggplot2 and extract the legend using the g_legend() function:
> library(ggplot2)
> main <- ggplot(iris, aes(x = Petal.Length, y = Petal.Width)) +
geom_point(alpha = .5 , aes(shape = Species, colour = Species))
> leg <- g_legend(main)
- Still using ggplot2, draw a histogram to fit the top margin:
> top <- ggplot(iris) +
geom_histogram(alpha = .3, aes( x = Petal.Length, fill = Species)) +
guides(fill = FALSE) + xlab('')
- And another histogram to fit the right margin:
> right <- ggplot(iris) +
geom_histogram(alpha = .3, aes( x = Petal.Width, fill = Species)) +
coord_flip() + guides(fill = FALSE) + xlab('')
- Arrange them all using gridExtra::grid.arrange():
> library(gridExtra)
> grid.arrange(top, leg, main + theme(legend.position = 'none'),
right, ncol=2, nrow=2, widths=c(4, 1), heights=c(1, 4))
See figure 2.10 for the resulting illustration:

Figure 2.10 - Marginal histograms draw with gridExtra.