Learn R Programming

⚠️There's a newer version (1.0.1) of this package.Take me there.

ggalign

This package extends ggplot2 by providing advanced tools for aligning and organizing multiple plots, particularly those that automatically reorder observations, such as dendrogram. It offers fine control over layout adjustment and plot annotations, enabling you to create complex, publication-quality visualizations while still using the familiar grammar of ggplot2.

Why use ggalign?

ggalign focuses on aligning observations across multiple plots. It leverages the "number of observations" in the vctrs package or NROW() function to maintain consistency in plot organization.

If you’ve ever struggled with aligning plots with self-contained ordering (like dendrogram), or applying consistent grouping or ordering across multiple plots (e.g., with k-means clustering), ggalign is designed to make this easier. The package integrates seamlessly with ggplot2, providing the flexibility to use its geoms, scales, and other components for complex visualizations.

Installation

You can install ggalign from CRAN using:

install.packages("ggalign")

Alternatively, install the development version from r-universe with:

install.packages("ggalign",
    repos = c("https://yunuuuu.r-universe.dev", "https://cloud.r-project.org")
)

or from GitHub with:

# install.packages("remotes")
remotes::install_github("Yunuuuu/ggalign")

Getting Started

The usage of ggalign is simple if you’re familiar with ggplot2 syntax, the typical workflow includes:

  • Initialize the layout using quad_layout() (ggheatmap()/ggside()) or stack_layout() (ggstack()).
  • Customize the layout with:
    • align_group(): Group observations into panel with a group variable.
    • align_kmeans(): Group observations into panel by kmeans.
    • align_order(): Reorder layout observations based on statistical weights or by manually specifying the observation index.
    • align_dendro(): Reorder or Group layout based on hierarchical clustering.
  • Adding plots with ggalign() or ggfree(), and then layer additional ggplot2 elements such as geoms, stats, or scales.

For documents of the release version, please see https://yunuuuu.github.io/ggalign/, for documents of the development version, please see https://yunuuuu.github.io/ggalign/dev/.

Basic example

Below, we’ll walk through a basic example of using ggalign to create a heatmap with a dendrogram.

library(ggalign)
#> Loading required package: ggplot2
set.seed(123)
small_mat <- matrix(rnorm(72), nrow = 9)
rownames(small_mat) <- paste0("row", seq_len(nrow(small_mat)))
colnames(small_mat) <- paste0("column", seq_len(ncol(small_mat)))

# initialize the heatmap layout, we can regard it as a normal ggplot object
my_heatplot <- ggheatmap(small_mat) +
    # we can directly modify geoms, scales and other ggplot2 components
    scale_fill_viridis_c() +
    # add annotation in the top
    anno_top() +
    # in the top annotation, we add a dendrogram, and split observations into 3 groups
    align_dendro(aes(color = branch), k = 3) +
    # in the dendrogram we add a point geom
    geom_point(aes(color = branch, y = y)) +
    # change color mapping for the dendrogram
    scale_color_brewer(palette = "Dark2")
my_heatplot
#> → heatmap built with `geom_tile()`

Marginal plots can also be created with similar syntax:

my_sideplot <- ggside(mpg, aes(displ, hwy, colour = class)) -
    # set default theme for all plots in the layout
    plot_theme(theme_bw()) +
    geom_point(size = 2) +
    # add top annotation
    anno_top(size = 0.3) -
    # set default theme for the top annotation
    plot_theme(theme_no_axes("tb")) +
    # add a plot in the top annotation
    ggfree() +
    geom_density(aes(displ, y = after_stat(density), colour = class), position = "stack") +
    anno_right(size = 0.3) -
    # set default theme for the right annotation
    plot_theme(theme_no_axes("lr")) +
    # add a plot in the right annotation
    ggfree() +
    geom_density(aes(x = after_stat(density), hwy, colour = class),
        position = "stack"
    ) +
    theme(axis.text.x = element_text(angle = 90, vjust = .5)) &
    scale_color_brewer(palette = "Dark2")
my_sideplot

Multiple heatmaps can be stacked together:

stack_alignv() +
    my_heatplot +
    my_heatplot
#> → heatmap built with `geom_tile()`
#> → heatmap built with `geom_tile()`

Similarly, multiple marginal plots can be stacked together:

stack_freev(sizes = c(1, 1, 0.3)) +
    my_sideplot +
    my_sideplot

Compare with other ggplot2 heatmap extension

ggalign offers advantages over extensions like ggheatmap by providing full compatibility with ggplot2. With ggalign, you can:

  • Seamlessly integrate ggplot2 geoms, stats, scales et al. into your layouts.
  • Align dendrograms even in facetted plots.
  • Easily create complex layouts, including multiple heatmaps arranged vertically or horizontally.

Compare with ComplexHeatmap

Pros

  • Full integration with the ggplot2 ecosystem.
  • Heatmap annotation axes and legends are automatically generated.
  • Dendrogram can be easily customized and colored.
  • Flexible control over plot size and spacing.
  • Can easily align with other ggplot2 plots by panel area.
  • Can easily extend for other clustering algorithm, or annotation plot.

Cons

Fewer Built-In Annotations: May require additional coding for specific annotations or customization compared to the extensive built-in annotation function in ComplexHeatmap.

More Complex Examples

Here are some more advanced visualizations using ggalign:

Copy Link

Version

Install

install.packages('ggalign')

Monthly Downloads

774

Version

0.0.5

License

MIT + file LICENSE

Issues

Pull Requests

Stars

Forks

Maintainer

Yun Peng

Last Published

November 14th, 2024

Functions in ggalign (0.0.5)

align_plots

Arrange multiple plots into a grid
Layout-class

A Layout object
active

Plot Adding Context Settings
dendrogram_data

Dengrogram x and y coordinates
fortify_data_frame.matrix

Build a data frame
fortify_data_frame

Build a data frame
free_align

Free from alignment
align_dendro

Reorder or Group observations based on hierarchical clustering
align

Create a New align Object
free_gg

Add ggplot to layout
fortify_data_frame.numeric

Build a data frame
ggwrap

Wrap Arbitrary Graphics to ggplot
patch

Convert Object into a Grob
hclust2

Generate Tree Structures with Hierarchical Clustering
patch.alignpatches

Convert Object into a Grob
area

Define the plotting areas in align_plots
layout_design

Define the grid to compose plots in
fortify_matrix.default

Build a Matrix
$,Layout-method

Subset a Layout object
layout_title

Annotate the whole layout
plot_align

Align Specifications in the Layout
patch.patch_ggplot

Convert Object into a Grob
plot_data

Plot data Specifications
fortify_stack

Build data for the stack layout
inset

Create a ggplot inset
heatmap_layout

Arrange Plots in a Heatmap
align_gg

Create ggplot object
patch.patchwork

Convert Object into a Grob
align_group

Group and align observations based on a group vector
read_example

Read Example Data
reexports

Objects exported from other packages
geom_pie

Pie charts
patch.formula

Convert Object into a Grob
patch.ggplot

Convert Object into a Grob
ggalign-package

ggalign: A 'ggplot2' Extension for Consistent Axis Alignment
fortify_data_frame.character

Build a data frame
patch.trellis

Convert Object into a Grob
patch_titles

Add patch titles to plot borders
align_reorder

Reorders layout observations based on specific statistics.
alignpatch

Prepare plots to be aligned with align_plots
fortify_data_frame.default

Build a data frame
fortify_matrix.MAF

Build a Matrix
layout-operator

Layout operator
layout_annotation

Modify components of the layout
quad_layout

Arrange Plots in the Quad-Side of a main plot
ggalignGrob

Generate a plot grob.
order2

Ordering Permutation
ggalign_attr

Get data from the ggalign attribute
patch.Heatmap

Convert Object into a Grob
patch.pheatmap

Convert Object into a Grob
patch.recordedplot

Convert Object into a Grob
quad_switch

Determine the Active Context of Quad-Layout
with_quad

Modify Context for the - Operator in quad_layout()
ggalign_stat

Get the statistics from the layout
fortify_matrix

Build a Matrix
is_layout

Reports whether x is layout object
ggoncoplot

Create OncoPrint Visualizations from Genetic Alteration Data
patch.grob

Convert Object into a Grob
quad_free

Arrange Plots in the Quad-Side of a main plot
quad_init

Initialize Quad-Layout Annotation
layer_order

Change the layer adding order
patch.patch

Convert Object into a Grob
show,Layout-method

Print Layout object
theme_ggalign

Theme for Layout Plots
theme_no_axes

Remove axis elements
stack_align

Arrange Plots Horizontally or Vertically
plot_theme

Plot default theme
quad_active

Determine the Active Context of Quad-Layout
stack_layout

Put plots horizontally or vertically
stack_switch

Determine the active context of stack layout
align_panel

Create ggplot object with layout panel data
align_kmeans

Split observations by k-means clustering groups.
align_order

Order observations based on weights