Code
library(ggalign)
#> Loading required package: ggplot2
#>
#> Attaching package: 'ggalign'
#> The following object is masked from 'package:ggplot2':
#>
#> element_polygon
This chapter shows simple usage examples of ggalign
.
library(ggalign)
#> Loading required package: ggplot2
#>
#> Attaching package: 'ggalign'
#> The following object is masked from 'package:ggplot2':
#>
#> element_polygon
The usage of data-free composition is simple: just create plots first then arrange plots together!
# Create individual plots
<- ggplot(mtcars) +
p1 geom_point(aes(mpg, disp)) +
ggtitle("Scatter Plot")
<- ggplot(mtcars) +
p2 geom_boxplot(aes(factor(cyl), mpg)) +
ggtitle("Box Plot")
<- ggplot(mtcars) +
p3 geom_histogram(aes(mpg), bins = 15) +
ggtitle("Histogram")
# Arrange plots in a grid
align_plots(p1, p2, p3, ncol = 2)
The align_plots()
function offers flexible control over grid dimensions, sizing, and layout specifications. You can control the arrangement with parameters like ncol
, nrow
, widths
, heights
, and even use area()
specifications for complex layouts.
ggalign
provides various options to control layout specifications, including whether to collect legend guides, align axes, and more. For more, see Part Data-Free Composition
.
A common use case for data-aware composition is combining a heatmap with a dendrogram. The dendrogram reveals hierarchical relationships among the data (e.g., samples or genes), and the heatmap is reordered to align with the dendrogram structure—ensuring consistent interpretation.
set.seed(123)
# Prepare heatmap matrix
<- matrix(
mat rnorm(200, mean = 5, sd = 2),
nrow = 20, ncol = 10,
dimnames = list(paste0("G", 1:20), paste0("S", 1:10))
)
Create a basic heatmap:
ggheatmap(mat)
#> → heatmap built with `geom_tile()`
With ggalign
, you can add elements using the same +
syntax as in ggplot2
. For example, to add a dendrogram above the heatmap:
ggheatmap(mat) +
anno_top() +
align_dendro()
#> → heatmap built with `geom_tile()`
This automatically reorders the heatmap rows or columns to reflect the hierarchical structure in the dendrogram.
While data-aware composition is the core strength of ggalign
, its full capabilities go beyond a single example. For more advanced features and finer control, see Part Data-Aware Composition
.
Use data-free composition when: - Combining unrelated plots for publication figures - Creating dashboard-style layouts - Arranging plots with different data sources - Simple spatial arrangement is sufficient
Use data-aware composition when: - Analyzing the same dataset from multiple perspectives - Creating heatmaps with annotations - Ensuring observation consistency across plots - Working with genomic, transcriptomic, or other omics data
This foundational understanding of ggalign’s two composition modes will guide you through the more advanced features covered in subsequent chapters.