For heatmap with ggplot2, I recently developed a ggplot2 extension ggalign 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.
if you are interested, please check it out at https://github.com/Yunuuuu/ggalign!
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/.
The development version now seamlessly integrates with maftools
and supports magick
rasterization.
library(ggalign)
ff <- data.frame(
Var1 = as.factor(c(
"V1", "V2", "V3", "V4", "V1", "V2", "V3", "V4", "V1",
"V2", "V3", "V4", "V1", "V2", "V3", "V4"
)),
Var2 = as.factor(c(
"V1", "V1", "V1", "V1", "V2", "V2", "V2", "V2", "V3",
"V3", "V3", "V3", "V4", "V4", "V4", "V4"
)),
value = c(
NA, 0.1, 0.2, 0.2,
0.4, NA, 0.3, 0.4,
0.5, 0.5, NA, 0.3,
0.2, 0.3, 0.3, NA
)
)
mat <- tibble::column_to_rownames(
tidyr::pivot_wider(ff, id_cols = Var1, names_from = Var2),
"Var1"
)
# the internal will convert the matrix to a long format data frame,
# and will set limits match your input matrix
ggheatmap(as.matrix(mat), aes(.x, .y), filling = FALSE) +
geom_raster(aes(fill = value), data = function(d) {
subset(d, .x > .y)
}) +
scale_fill_distiller(palette = "Blues") +
ggnewscale::new_scale_fill() +
geom_raster(aes(fill = value), data = function(d) {
subset(d, .y > .x)
}) +
scale_fill_distiller(palette = "Reds")