Home | Blog | Software | Publications | GitHub


Support raster image in heatmaps

Saving heatmaps in PDF format is kind of best parctice to preserve the quality. However, when there are too many rows (say, > 10000), the output PDF file size would be huge and it takes time and memory to read and show the plot.

Rendering heatmaps as raster images will effectively reduce the file size. In ComplexHeatmap package, Heatmap() function, there are four options which control how to generate the raster image: use_raster, raster_device, raster_quality, raster_device_param.

set.seed(123)
mat = matrix(rnorm(10000*100), ncol = 100)

Following makes heatmap with and without raster images.

library(ComplexHeatmap)
pdf("heatmap.pdf", width = 8, height = 8)
Heatmap(mat, cluster_rows = FALSE, cluster_columns = FALSE)
dev.off()

pdf("heatmap_raster_by_png.pdf", width = 8, height = 8)
Heatmap(mat, cluster_rows = FALSE, cluster_columns = FALSE, use_raster = TRUE, raster_device = "png")
dev.off()

pdf("heatmap_raster_by_jpeg.pdf", width = 8, height = 8)
Heatmap(mat, cluster_rows = FALSE, cluster_columns = FALSE, use_raster = TRUE, raster_device = "jpeg")
dev.off()

pdf("heatmap_raster_by_tiff.pdf", width = 8, height = 8)
Heatmap(mat, cluster_rows = FALSE, cluster_columns = FALSE, use_raster = TRUE, raster_device = "tiff")
dev.off()

pdf("heatmap_raster_by_CairoPNG.pdf", width = 8, height = 8)
Heatmap(mat, cluster_rows = FALSE, cluster_columns = FALSE, use_raster = TRUE, raster_device = "CairoPNG")
dev.off()

pdf("heatmap_raster_by_CairoJPEG.pdf", width = 8, height = 8)
Heatmap(mat, cluster_rows = FALSE, cluster_columns = FALSE, use_raster = TRUE, raster_device = "CairoJPEG")
dev.off()

And the difference between these PDF files:

all_files = c("heatmap.pdf", "heatmap_raster_by_png.pdf", 
              "heatmap_raster_by_jpeg.pdf", "heatmap_raster_by_tiff.pdf",
              "heatmap_raster_by_CairoPNG.pdf", "heatmap_raster_by_CairoJPEG.pdf")
fs = file.size(all_files)
names(fs) = all_files
sapply(fs, function(x) paste(round(x/1024), "KB"))
##                     heatmap.pdf       heatmap_raster_by_png.pdf 
##                       "6652 KB"                        "192 KB" 
##      heatmap_raster_by_jpeg.pdf      heatmap_raster_by_tiff.pdf 
##                        "779 KB"                        "192 KB" 
##  heatmap_raster_by_CairoPNG.pdf heatmap_raster_by_CairoJPEG.pdf 
##                        "141 KB"                        "765 KB"

The ratio to heatmap.pdf:

fs[-1]/fs[1]
##       heatmap_raster_by_png.pdf      heatmap_raster_by_jpeg.pdf 
##                           0.029                           0.117 
##      heatmap_raster_by_tiff.pdf  heatmap_raster_by_CairoPNG.pdf 
##                           0.029                           0.021 
## heatmap_raster_by_CairoJPEG.pdf 
##                           0.115