{"id":7693,"date":"2018-10-18T23:08:01","date_gmt":"2018-10-18T21:08:01","guid":{"rendered":"https:\/\/www.datanovia.com\/en\/?post_type=dt_lessons&#038;p=7693"},"modified":"2020-04-25T23:17:07","modified_gmt":"2020-04-25T22:17:07","slug":"heatmap-in-r-static-and-interactive-visualization","status":"publish","type":"dt_lessons","link":"https:\/\/www.datanovia.com\/en\/lessons\/heatmap-in-r-static-and-interactive-visualization\/","title":{"rendered":"Heatmap in R: Static and Interactive Visualization"},"content":{"rendered":"<div id=\"rdoc\">\n<p>A <strong>heatmap<\/strong> (or <strong>heat map<\/strong>) is another way to visualize hierarchical clustering. It\u2019s also called a false colored image, where data values are transformed to color scale.<\/p>\n<p>Heat maps allow us to simultaneously visualize clusters of samples and features. First hierarchical clustering is done of both the rows and the columns of the data matrix. The columns\/rows of the data matrix are re-ordered according to the hierarchical clustering result, putting similar observations close to each other. The blocks of \u2018high\u2019 and \u2018low\u2019 values are adjacent in the data matrix. Finally, a color scheme is applied for the visualization and the data matrix is displayed. Visualizing the data matrix in this way can help to find the variables that appear to be characteristic for each sample cluster.<\/p>\n<div class=\"block\">\n<p>Previously, we described how to visualize dendrograms. Here, we\u2019ll demonstrate how to draw and arrange a heatmap in R.<\/p>\n<\/div>\n<p>Contents:<\/p>\n<div id=\"TOC\">\n<ul>\n<li><a href=\"#r-packagesfunctions-for-drawing-heatmaps\">R Packages\/functions for drawing heatmaps<\/a><\/li>\n<li><a href=\"#data-preparation\">Data preparation<\/a><\/li>\n<li><a href=\"#r-base-heatmap-heatmap\">R base heatmap: heatmap()<\/a><\/li>\n<li><a href=\"#enhanced-heat-maps-heatmap.2\">Enhanced heat maps: heatmap.2()<\/a><\/li>\n<li><a href=\"#pretty-heat-maps-pheatmap\">Pretty heat maps: pheatmap()<\/a><\/li>\n<li><a href=\"#interactive-heat-maps-d3heatmap\">Interactive heat maps: d3heatmap()<\/a><\/li>\n<li><a href=\"#enhancing-heatmaps-using-dendextend\">Enhancing heatmaps using dendextend<\/a><\/li>\n<li><a href=\"#complex-heatmap\">Complex heatmap<\/a>\n<ul>\n<li><a href=\"#simple-heatmap\">Simple heatmap<\/a><\/li>\n<li><a href=\"#splitting-heatmap-by-rows\">Splitting heatmap by rows<\/a><\/li>\n<li><a href=\"#heatmap-annotation\">Heatmap annotation<\/a><\/li>\n<\/ul>\n<\/li>\n<li><a href=\"#application-to-gene-expression-matrix\">Application to gene expression matrix<\/a><\/li>\n<li><a href=\"#visualizing-the-distribution-of-columns-in-matrix\">Visualizing the distribution of columns in matrix<\/a><\/li>\n<li><a href=\"#summary\">Summary<\/a><\/li>\n<\/ul>\n<\/div>\n<div class='dt-sc-hr-invisible-medium  '><\/div>\n<div class='dt-sc-ico-content type1'><div class='custom-icon' ><a href='https:\/\/www.datanovia.com\/en\/product\/practical-guide-to-cluster-analysis-in-r\/' target='_blank'><span class='fa fa-book'><\/span><\/a><\/div><h4><a href='https:\/\/www.datanovia.com\/en\/product\/practical-guide-to-cluster-analysis-in-r\/' target='_blank'> Related Book <\/a><\/h4>Practical Guide to Cluster Analysis in R<\/div>\n<div class='dt-sc-hr-invisible-medium  '><\/div>\n<div id=\"r-packagesfunctions-for-drawing-heatmaps\" class=\"section level2\">\n<h2>R Packages\/functions for drawing heatmaps<\/h2>\n<p>There are a multiple numbers of R packages and functions for drawing interactive and static heatmaps, including:<\/p>\n<ul>\n<li><em>heatmap<\/em>() [R base function, <em>stats<\/em> package]: Draws a simple heatmap<\/li>\n<li><em>heatmap.2<\/em>() [<em>gplots<\/em> R package]: Draws an enhanced heatmap compared to the R base function.<\/li>\n<li><em>pheatmap<\/em>() [<em>pheatmap<\/em> R package]: Draws pretty heatmaps and provides more control to change the appearance of heatmaps.<\/li>\n<li><em>d3heatmap<\/em>() [<em>d3heatmap<\/em> R package]: Draws an interactive\/clickable heatmap<\/li>\n<li><em>Heatmap<\/em>() [<em>ComplexHeatmap<\/em> R\/Bioconductor package]: Draws, annotates and arranges complex heatmaps (very useful for genomic data analysis)<\/li>\n<\/ul>\n<p>Here, we start by describing the 5 R functions for drawing heatmaps. Next, we\u2019ll focus on the <em>ComplexHeatmap<\/em> package, which provides a flexible solution to arrange and annotate multiple heatmaps. It allows also to visualize the association between different data from different sources.<\/p>\n<\/div>\n<div id=\"data-preparation\" class=\"section level2\">\n<h2>Data preparation<\/h2>\n<p>We use mtcars data as a demo data set. We start by standardizing the data to make variables comparable:<\/p>\n<pre class=\"r\"><code>df &lt;- scale(mtcars)<\/code><\/pre>\n<\/div>\n<div id=\"r-base-heatmap-heatmap\" class=\"section level2\">\n<h2>R base heatmap: heatmap()<\/h2>\n<p>The built-in R <em>heatmap<\/em>() function [in <em>stats<\/em> package] can be used.<\/p>\n<p>A simplified format is:<\/p>\n<pre class=\"r\"><code>heatmap(x, scale = \"row\")<\/code><\/pre>\n<ul>\n<li><strong>x<\/strong>: a numeric matrix<\/li>\n<li><strong>scale<\/strong>: a character indicating if the values should be centered and scaled in either the row direction or the column direction, or none. Allowed values are in c(\u201crow\u201d, \u201ccolumn\u201d, \u201cnone\u201d). Default is \u201crow\u201d.<\/li>\n<\/ul>\n<pre class=\"r\"><code># Default plot\r\nheatmap(df, scale = \"none\")<\/code><\/pre>\n<p><img decoding=\"async\" src=\"https:\/\/www.datanovia.com\/en\/wp-content\/uploads\/dn-tutorials\/003-hierarchical-clustering-in-r\/figures\/006-heatmap-r-base-heatmap-1.png\" width=\"518.4\" \/><\/p>\n<div class=\"success\">\n<p>In the plot above, high values are in red and low values are in yellow.<\/p>\n<\/div>\n<p>It\u2019s possible to specify a color palette using the argument <em>col<\/em>, which can be defined as follow:<\/p>\n<ul>\n<li>Using custom colors:<\/li>\n<\/ul>\n<pre class=\"r\"><code>col&lt;- colorRampPalette(c(\"red\", \"white\", \"blue\"))(256)<\/code><\/pre>\n<ul>\n<li>Or, using RColorBrewer color palette:<\/li>\n<\/ul>\n<pre class=\"r\"><code>library(\"RColorBrewer\")\r\ncol &lt;- colorRampPalette(brewer.pal(10, \"RdYlBu\"))(256)<\/code><\/pre>\n<p>Additionally, you can use the argument <em>RowSideColors<\/em> and <em>ColSideColors<\/em> to annotate rows and columns, respectively.<\/p>\n<p>For example, in the the R code below will customize the heatmap as follow:<\/p>\n<ol style=\"list-style-type: decimal;\">\n<li>An RColorBrewer color palette name is used to change the appearance<\/li>\n<li>The argument <em>RowSideColors<\/em> and <em>ColSideColors<\/em> are used to annotate rows and columns respectively. The expected values for these options are a vector containing color names specifying the classes for rows\/columns.<\/li>\n<\/ol>\n<pre class=\"r\"><code># Use RColorBrewer color palette names\r\nlibrary(\"RColorBrewer\")\r\ncol &lt;- colorRampPalette(brewer.pal(10, \"RdYlBu\"))(256)\r\nheatmap(df, scale = \"none\", col =  col, \r\n        RowSideColors = rep(c(\"blue\", \"pink\"), each = 16),\r\n        ColSideColors = c(rep(\"purple\", 5), rep(\"orange\", 6)))<\/code><\/pre>\n<p><img decoding=\"async\" src=\"https:\/\/www.datanovia.com\/en\/wp-content\/uploads\/dn-tutorials\/003-hierarchical-clustering-in-r\/figures\/006-heatmap-r-base-heatmap-color-1.png\" width=\"518.4\" \/><\/p>\n<\/div>\n<div id=\"enhanced-heat-maps-heatmap.2\" class=\"section level2\">\n<h2>Enhanced heat maps: heatmap.2()<\/h2>\n<p>The function <em>heatmap.2<\/em>() [in <em>gplots<\/em> package] provides many extensions to the standard R <em>heatmap<\/em>() function presented in the previous section.<\/p>\n<pre class=\"r\"><code># install.packages(\"gplots\")\r\nlibrary(\"gplots\")\r\nheatmap.2(df, scale = \"none\", col = bluered(100), \r\n          trace = \"none\", density.info = \"none\")<\/code><\/pre>\n<p><img decoding=\"async\" src=\"https:\/\/www.datanovia.com\/en\/wp-content\/uploads\/dn-tutorials\/003-hierarchical-clustering-in-r\/figures\/006-heatmap-gplots-heatmap-2-1.png\" width=\"518.4\" \/><\/p>\n<p>Other arguments can be used including:<\/p>\n<ul>\n<li><em>labRow<\/em>, <em>labCol<\/em><\/li>\n<li><em>hclustfun<\/em>: hclustfun=function(x) hclust(x, method=\u201cward\u201d)<\/li>\n<\/ul>\n<p>In the R code above, the <em>bluered<\/em>() function [in <em>gplots<\/em> package] is used to generate a smoothly varying set of colors. You can also use the following color generator functions:<\/p>\n<ul>\n<li><em>colorpanel<\/em>(n, low, mid, high)\n<ul>\n<li><em>n<\/em>: Desired number of color elements to be generated<\/li>\n<li><em>low, mid, high<\/em>: Colors to use for the Lowest, middle, and highest values. mid may be omitted.<\/li>\n<\/ul>\n<\/li>\n<li><em>redgreen<\/em>(n), <em>greenred<\/em>(n), <em>bluered<\/em>(n) and <em>redblue<\/em>(n)<\/li>\n<\/ul>\n<\/div>\n<div id=\"pretty-heat-maps-pheatmap\" class=\"section level2\">\n<h2>Pretty heat maps: pheatmap()<\/h2>\n<p>First, install the <em>pheatmap<\/em> package: install.packages(\u201cpheatmap\u201d); then type this:<\/p>\n<pre class=\"r\"><code>library(\"pheatmap\")\r\npheatmap(df, cutree_rows = 4)<\/code><\/pre>\n<p><img decoding=\"async\" src=\"https:\/\/www.datanovia.com\/en\/wp-content\/uploads\/dn-tutorials\/003-hierarchical-clustering-in-r\/images\/pheatmap.png\" alt=\"Heatmap\" \/><\/p>\n<p>Arguments are available for changing the default clustering metric (\u201ceuclidean\u201d) and method (\u201ccomplete\u201d). It\u2019s also possible to annotate rows and columns using grouping variables.<\/p>\n<\/div>\n<div id=\"interactive-heat-maps-d3heatmap\" class=\"section level2\">\n<h2>Interactive heat maps: d3heatmap()<\/h2>\n<p>First, install the <em>d3heatmap<\/em> package: install.packages(\u201cd3heatmap\u201d); then type this:<\/p>\n<pre class=\"r\"><code>library(\"d3heatmap\")\r\nd3heatmap(scale(mtcars), colors = \"RdYlBu\",\r\n          k_row = 4, # Number of groups in rows\r\n          k_col = 2 # Number of groups in columns\r\n          )<\/code><\/pre>\n<p><img decoding=\"async\" src=\"https:\/\/www.datanovia.com\/en\/wp-content\/uploads\/dn-tutorials\/003-hierarchical-clustering-in-r\/images\/interactive-heatmap.png\" alt=\"Interactive heatmap\" \/><\/p>\n<p>The <em>d3heamap<\/em>() function makes it possible to:<\/p>\n<ul>\n<li>Put the mouse on a heatmap cell of interest to view the row and the column names as well as the corresponding value.<\/li>\n<li>Select an area for zooming. After zooming, click on the heatmap again to go back to the previous display<\/li>\n<\/ul>\n<\/div>\n<div id=\"enhancing-heatmaps-using-dendextend\" class=\"section level2\">\n<h2>Enhancing heatmaps using dendextend<\/h2>\n<p>The package <em>dendextend<\/em> can be used to enhance functions from other packages. The <em>mtcars<\/em> data is used in the following sections. We\u2019ll start by defining the order and the appearance for rows and columns using dendextend. These results are used in others functions from others packages.<\/p>\n<p>The order and the appearance for rows and columns can be defined as follow:<\/p>\n<pre class=\"r\"><code>library(dendextend)\r\n# order for rows\r\nRowv  &lt;- mtcars %&gt;% scale %&gt;% dist %&gt;% hclust %&gt;% as.dendrogram %&gt;%\r\n   set(\"branches_k_color\", k = 3) %&gt;% set(\"branches_lwd\", 1.2) %&gt;%\r\n   ladderize\r\n# Order for columns: We must transpose the data\r\nColv  &lt;- mtcars %&gt;% scale %&gt;% t %&gt;% dist %&gt;% hclust %&gt;% as.dendrogram %&gt;%\r\n   set(\"branches_k_color\", k = 2, value = c(\"orange\", \"blue\")) %&gt;%\r\n   set(\"branches_lwd\", 1.2) %&gt;%\r\n   ladderize<\/code><\/pre>\n<p>The arguments above can be used in the functions below:<\/p>\n<ol style=\"list-style-type: decimal;\">\n<li>The standard <em>heatmap<\/em>() function [in <em>stats<\/em> package]:<\/li>\n<\/ol>\n<pre class=\"r\"><code>heatmap(scale(mtcars), Rowv = Rowv, Colv = Colv,\r\n        scale = \"none\")<\/code><\/pre>\n<ol style=\"list-style-type: decimal;\" start=\"2\">\n<li>The enhanced <em>heatmap.2<\/em>() function [in <em>gplots<\/em> package]:<\/li>\n<\/ol>\n<pre class=\"r\"><code>library(gplots)\r\nheatmap.2(scale(mtcars), scale = \"none\", col = bluered(100), \r\n          Rowv = Rowv, Colv = Colv,\r\n          trace = \"none\", density.info = \"none\")<\/code><\/pre>\n<ol style=\"list-style-type: decimal;\" start=\"3\">\n<li>The interactive heatmap generator <em>d3heatmap<\/em>() function [in <em>d3heatmap<\/em> package]:<\/li>\n<\/ol>\n<pre class=\"r\"><code>library(\"d3heatmap\")\r\nd3heatmap(scale(mtcars), colors = \"RdBu\",\r\n          Rowv = Rowv, Colv = Colv)<\/code><\/pre>\n<\/div>\n<div id=\"complex-heatmap\" class=\"section level2\">\n<h2>Complex heatmap<\/h2>\n<p><strong>ComplexHeatmap<\/strong> is an R\/bioconductor package, developed by Zuguang Gu, which provides a flexible solution to arrange and annotate multiple heatmaps. It allows also to visualize the association between different data from different sources.<\/p>\n<p>It can be installed as follow:<\/p>\n<pre class=\"r\"><code>if (!requireNamespace(\"BiocManager\", quietly = TRUE))\r\n    install.packages(\"BiocManager\")\r\nBiocManager::install(\"ComplexHeatmap\")<\/code><\/pre>\n<div id=\"simple-heatmap\" class=\"section level3\">\n<h3>Simple heatmap<\/h3>\n<p>You can draw a simple heatmap as follow:<\/p>\n<pre class=\"r\"><code>library(ComplexHeatmap)\r\nHeatmap(df, \r\n        name = \"mtcars\", #title of legend\r\n        column_title = \"Variables\", row_title = \"Samples\",\r\n        row_names_gp = gpar(fontsize = 7) # Text size for row names\r\n        )<\/code><\/pre>\n<p><img decoding=\"async\" src=\"https:\/\/www.datanovia.com\/en\/wp-content\/uploads\/dn-tutorials\/003-hierarchical-clustering-in-r\/figures\/006-heatmap-simple-heatmap-1.png\" width=\"518.4\" \/><\/p>\n<p>Additional arguments:<\/p>\n<ol style=\"list-style-type: decimal;\">\n<li>show_row_names, show_column_names: whether to show row and column names, respectively. Default value is TRUE<\/li>\n<li>show_row_hclust, show_column_hclust: logical value; whether to show row and column clusters. Default is TRUE<\/li>\n<li>clustering_distance_rows, clustering_distance_columns: metric for clustering: \u201ceuclidean\u201d, \u201cmaximum\u201d, \u201cmanhattan\u201d, \u201ccanberra\u201d, \u201cbinary\u201d, \u201cminkowski\u201d, \u201cpearson\u201d, \u201cspearman\u201d, \u201ckendall\u201d)<\/li>\n<li>clustering_method_rows, clustering_method_columns: clustering methods: \u201cward.D\u201d, \u201cward.D2\u201d, \u201csingle\u201d, \u201ccomplete\u201d, \u201caverage\u201d, \u2026 (see <strong>?hclust<\/strong>).<\/li>\n<\/ol>\n<p>To specify a custom colors, you must use the the <em>colorRamp2<\/em>() function [<em>circlize<\/em> package], as follow:<\/p>\n<pre class=\"r\"><code>library(circlize)\r\nmycols &lt;- colorRamp2(breaks = c(-2, 0, 2), \r\n                    colors = c(\"green\", \"white\", \"red\"))\r\nHeatmap(df, name = \"mtcars\", col = mycols)<\/code><\/pre>\n<p>It\u2019s also possible to use <strong>RColorBrewer<\/strong> color palettes:<\/p>\n<pre class=\"r\"><code>library(\"circlize\")\r\nlibrary(\"RColorBrewer\")\r\nHeatmap(df, name = \"mtcars\",\r\n        col = colorRamp2(c(-2, 0, 2), brewer.pal(n=3, name=\"RdBu\")))<\/code><\/pre>\n<p>We can also customize the appearance of dendograms using the function <em>color_branches<\/em>() [<em>dendextend<\/em> package]:<\/p>\n<pre class=\"r\"><code>library(dendextend)\r\nrow_dend = hclust(dist(df)) # row clustering\r\ncol_dend = hclust(dist(t(df))) # column clustering\r\nHeatmap(df, name = \"mtcars\", \r\n        row_names_gp = gpar(fontsize = 6.5),\r\n        cluster_rows = color_branches(row_dend, k = 4),\r\n        cluster_columns = color_branches(col_dend, k = 2))<\/code><\/pre>\n<p><img decoding=\"async\" src=\"https:\/\/www.datanovia.com\/en\/wp-content\/uploads\/dn-tutorials\/003-hierarchical-clustering-in-r\/figures\/006-heatmap-dendogram-appearance-1.png\" width=\"518.4\" \/><\/p>\n<\/div>\n<div id=\"splitting-heatmap-by-rows\" class=\"section level3\">\n<h3>Splitting heatmap by rows<\/h3>\n<p>You can split the heatmap using either the k-means algorithm or a grouping variable.<\/p>\n<div class=\"notice\">\n<p>It\u2019s important to use the set.seed() function when performing k-means so that the results obtained can be reproduced precisely at a later time.<\/p>\n<\/div>\n<ul>\n<li>To split the dendrogram using k-means, type this:<\/li>\n<\/ul>\n<pre class=\"r\"><code># Divide into 2 groups\r\nset.seed(2)\r\nHeatmap(df, name = \"mtcars\", k = 2)<\/code><\/pre>\n<ul>\n<li>To split by a grouping variable, use the argument <em>split<\/em>. In the following example we\u2019ll use the levels of the factor variable cyl [in mtcars data set] to split the heatmap by rows. Recall that the column cyl corresponds to the number of cylinders.<\/li>\n<\/ul>\n<pre class=\"r\"><code># split by a vector specifying rowgroups\r\nHeatmap(df, name = \"mtcars\", split = mtcars$cyl,\r\n        row_names_gp = gpar(fontsize = 7))<\/code><\/pre>\n<p><img decoding=\"async\" src=\"https:\/\/www.datanovia.com\/en\/wp-content\/uploads\/dn-tutorials\/003-hierarchical-clustering-in-r\/figures\/006-heatmap-split-heatmap-1.png\" width=\"518.4\" \/><\/p>\n<div class=\"notice\">\n<p>Note that, <em>split<\/em> can be also a data frame in which different combinations of levels split the rows of the heatmap.<\/p>\n<\/div>\n<pre class=\"r\"><code># Split by combining multiple variables\r\nHeatmap(df, name =\"mtcars\", \r\n        split = data.frame(cyl = mtcars$cyl, am = mtcars$am),\r\n        row_names_gp = gpar(fontsize = 7))<\/code><\/pre>\n<p><img decoding=\"async\" src=\"https:\/\/www.datanovia.com\/en\/wp-content\/uploads\/dn-tutorials\/003-hierarchical-clustering-in-r\/figures\/006-heatmap-split-heatmap-multiple-variables-1.png\" width=\"518.4\" \/><\/p>\n<ul>\n<li>It\u2019s also possible to combine km and split:<\/li>\n<\/ul>\n<pre class=\"r\"><code>Heatmap(df, name =\"mtcars\", col = mycol,\r\n        km = 2, split =  mtcars$cyl)<\/code><\/pre>\n<ul>\n<li>If you want to use other partitioning method, rather than k-means, you can easily do it by just assigning the partitioning vector to split. In the R code below, we\u2019ll use <em>pam<\/em>() function [cluster package]. pam() stands for Partitioning of the data into k clusters \u201caround medoids\u201d, a more robust version of K-means.<\/li>\n<\/ul>\n<pre class=\"r\"><code># install.packages(\"cluster\")\r\nlibrary(\"cluster\")\r\nset.seed(2)\r\npa = pam(df, k = 3)\r\nHeatmap(df, name = \"mtcars\", col = mycol,\r\n        split = paste0(\"pam\", pa$clustering))<\/code><\/pre>\n<\/div>\n<div id=\"heatmap-annotation\" class=\"section level3\">\n<h3>Heatmap annotation<\/h3>\n<p>The <em>HeatmapAnnotation<\/em> class is used to define annotation on row or column. A simplified format is:<\/p>\n<pre class=\"r\"><code>HeatmapAnnotation(df, name, col, show_legend)<\/code><\/pre>\n<ul>\n<li><strong>df<\/strong>: a data.frame with column names<\/li>\n<li><strong>name<\/strong>: the name of the heatmap annotation<\/li>\n<li><strong>col<\/strong>: a list of colors which contains color mapping to columns in df<\/li>\n<\/ul>\n<p>For the example below, we\u2019ll transpose our data to have the observations in columns and the variables in rows.<\/p>\n<pre class=\"r\"><code>df &lt;- t(df)<\/code><\/pre>\n<div id=\"simple-annotation\" class=\"section level4\">\n<h4>Simple annotation<\/h4>\n<p>A vector, containing discrete or continuous values, is used to annotate rows or columns. We\u2019ll use the qualitative variables <em>cyl<\/em> (levels = \u201c4\u201d, \u201c5\u201d and \u201c8\u201d) and <em>am<\/em> (levels = \u201c0\u201d and \u201c1\u201d), and the continuous variable <em>mpg<\/em> to annotate columns.<\/p>\n<p>For each of these 3 variables, custom colors are defined as follow:<\/p>\n<pre class=\"r\"><code># Define colors for each levels of qualitative variables\r\n# Define gradient color for continuous variable (mpg)\r\ncol = list(cyl = c(\"4\" = \"green\", \"6\" = \"gray\", \"8\" = \"darkred\"),\r\n            am = c(\"0\" = \"yellow\", \"1\" = \"orange\"),\r\n            mpg = circlize::colorRamp2(c(17, 25), \r\n                                       c(\"lightblue\", \"purple\")) )\r\n# Create the heatmap annotation\r\nha &lt;- HeatmapAnnotation(\r\n  cyl = mtcars$cyl, am = mtcars$am, mpg = mtcars$mpg,\r\n  col = col\r\n)\r\n\r\n# Combine the heatmap and the annotation\r\nHeatmap(df, name = \"mtcars\",\r\n        top_annotation = ha)<\/code><\/pre>\n<p><img decoding=\"async\" src=\"https:\/\/www.datanovia.com\/en\/wp-content\/uploads\/dn-tutorials\/003-hierarchical-clustering-in-r\/figures\/006-heatmap-heatmap-annotation-1.png\" width=\"518.4\" \/><\/p>\n<div class=\"block\">\n<p>It\u2019s possible to hide the annotation legend using the argument <em>show_legend = FALSE<\/em> as follow:<\/p>\n<pre class=\"r\"><code>ha &lt;- HeatmapAnnotation(\r\n  cyl = mtcars$cyl, am = mtcars$am, mpg = mtcars$mpg, \r\n  col = col, show_legend = FALSE\r\n  )\r\nHeatmap(df, name = \"mtcars\", top_annotation = ha)<\/code><\/pre>\n<\/div>\n<\/div>\n<div id=\"complex-annotation\" class=\"section level4\">\n<h4>Complex annotation<\/h4>\n<p>In this section we\u2019ll see how to combine heatmap and some basic graphs to show the data distribution. For simple annotation graphics, the following functions can be used: <em>anno_points<\/em>(), <em>anno_barplot<\/em>(), <em>anno_boxplot<\/em>(), <em>anno_density<\/em>() and <em>anno_histogram<\/em>().<\/p>\n<p>An example is shown below:<\/p>\n<pre class=\"r\"><code># Define some graphics to display the distribution of columns\r\n.hist = anno_histogram(df, gp = gpar(fill = \"lightblue\"))\r\n.density = anno_density(df, type = \"line\", gp = gpar(col = \"blue\"))\r\nha_mix_top = HeatmapAnnotation(\r\n  hist = .hist, density = .density,\r\n  height = unit(3.8, \"cm\")\r\n  )\r\n# Define some graphics to display the distribution of rows\r\n.violin = anno_density(df, type = \"violin\", \r\n                       gp = gpar(fill = \"lightblue\"), which = \"row\")\r\n.boxplot = anno_boxplot(df, which = \"row\")\r\nha_mix_right = HeatmapAnnotation(violin = .violin, bxplt = .boxplot,\r\n                              which = \"row\", width = unit(4, \"cm\"))\r\n# Combine annotation with heatmap\r\nHeatmap(df, name = \"mtcars\", \r\n        column_names_gp = gpar(fontsize = 8),\r\n        top_annotation = ha_mix_top) + ha_mix_right<\/code><\/pre>\n<p><img decoding=\"async\" src=\"https:\/\/www.datanovia.com\/en\/wp-content\/uploads\/dn-tutorials\/003-hierarchical-clustering-in-r\/images\/complex-heatmap-annotation.png\" alt=\"Complex heatmap annotation\" \/><\/p>\n<\/div>\n<div id=\"combining-multiple-heatmaps\" class=\"section level4\">\n<h4>Combining multiple heatmaps<\/h4>\n<p>Multiple heatmaps can be arranged as follow:<\/p>\n<pre class=\"r\"><code># Heatmap 1\r\nht1 = Heatmap(df, name = \"ht1\", km = 2,\r\n              column_names_gp = gpar(fontsize = 9))\r\n# Heatmap 2\r\nht2 = Heatmap(df, name = \"ht2\", \r\n        col = circlize::colorRamp2(c(-2, 0, 2), c(\"green\", \"white\", \"red\")),\r\n        column_names_gp = gpar(fontsize = 9))\r\n# Combine the two heatmaps\r\nht1 + ht2<\/code><\/pre>\n<p><img decoding=\"async\" src=\"https:\/\/www.datanovia.com\/en\/wp-content\/uploads\/dn-tutorials\/003-hierarchical-clustering-in-r\/images\/combine-multiple-heatmaps.png\" alt=\"Combine multiple heatmaps\" \/><\/p>\n<div class=\"notice\">\n<p>You can use the option width = unit(3, \u201ccm\u201d)) to control the size of the heatmaps.<\/p>\n<\/div>\n<div class=\"warning\">\n<p>Note that when combining multiple heatmaps, the first heatmap is considered as the main heatmap. Some settings of the remaining heatmaps are auto-adjusted according to the setting of the main heatmap. These include: removing row clusters and titles, and adding splitting.<\/p>\n<\/div>\n<div style=\"page-break-after: always;\"><\/div>\n<p>The <em>draw<\/em>() function can be used to customize the appearance of the final image:<\/p>\n<pre class=\"r\"><code>draw(ht1 + ht2, \r\n    row_title = \"Two heatmaps, row title\", \r\n    row_title_gp = gpar(col = \"red\"),\r\n    column_title = \"Two heatmaps, column title\", \r\n    column_title_side = \"bottom\",\r\n    # Gap between heatmaps\r\n    gap = unit(0.5, \"cm\"))<\/code><\/pre>\n<div class=\"notice\">\n<p>Legends can be removed using the arguments <em>show_heatmap_legend = FALSE<\/em>, <em>show_annotation_legend = FALSE<\/em>.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div id=\"application-to-gene-expression-matrix\" class=\"section level2\">\n<h2>Application to gene expression matrix<\/h2>\n<p>In gene expression data, rows are genes and columns are samples. More information about genes can be attached after the expression heatmap such as gene length and type of genes.<\/p>\n<pre class=\"r\"><code>expr &lt;- readRDS(paste0(system.file(package = \"ComplexHeatmap\"),\r\n                      \"\/extdata\/gene_expression.rds\"))\r\nmat &lt;- as.matrix(expr[, grep(\"cell\", colnames(expr))])\r\ntype &lt;- gsub(\"s\\\\d+_\", \"\", colnames(mat))\r\nha = HeatmapAnnotation(\r\n  df = data.frame(type = type),\r\n   annotation_height = unit(4, \"mm\")\r\n  )\r\n\r\nHeatmap(mat, name = \"expression\", km = 5, top_annotation = ha,\r\n    show_row_names = FALSE, show_column_names = FALSE) +\r\nHeatmap(expr$length, name = \"length\", width = unit(5, \"mm\"),\r\n    col = circlize::colorRamp2(c(0, 100000), c(\"white\", \"orange\"))) +\r\nHeatmap(expr$type, name = \"type\", width = unit(5, \"mm\")) +\r\nHeatmap(expr$chr, name = \"chr\", width = unit(5, \"mm\"),\r\n    col = circlize::rand_color(length(unique(expr$chr))))<\/code><\/pre>\n<p><img decoding=\"async\" src=\"https:\/\/www.datanovia.com\/en\/wp-content\/uploads\/dn-tutorials\/003-hierarchical-clustering-in-r\/images\/heatmap-gene-expression-data.png\" alt=\"Heatmap gene expression data\" \/><\/p>\n<div class=\"notice\">\n<p>It\u2019s also possible to visualize genomic alterations and to integrate different molecular levels (gene expression, DNA methylation, \u2026). Read the vignette, on Bioconductor, for further examples.<\/p>\n<\/div>\n<\/div>\n<div id=\"visualizing-the-distribution-of-columns-in-matrix\" class=\"section level2\">\n<h2>Visualizing the distribution of columns in matrix<\/h2>\n<pre class=\"r\"><code>densityHeatmap(scale(mtcars))<\/code><\/pre>\n<p><img decoding=\"async\" src=\"https:\/\/www.datanovia.com\/en\/wp-content\/uploads\/dn-tutorials\/003-hierarchical-clustering-in-r\/images\/matrix-column-distribution.png\" alt=\"Matrix column distribution\" \/><\/p>\n<p>The dashed lines on the heatmap correspond to the five quantile numbers. The text for the five quantile levels are added in the right of the heatmap.<\/p>\n<\/div>\n<div id=\"summary\" class=\"section level2\">\n<h2>Summary<\/h2>\n<p>We described many functions for drawing heatmaps in R (from basic to complex heatmaps). A basic heatmap can be produced using either the R base function <em>heatmap<\/em>() or the function <em>heatmap.2<\/em>() [in the <em>gplots<\/em> package].<br \/>\nThe <em>pheatmap<\/em>() function, in the package of the same name, creates pretty heatmaps, where ones has better control over some graphical parameters such as cell size.<\/p>\n<p>The <em>Heatmap<\/em>() function [in <em>ComplexHeatmap<\/em> package] allows us to easily, draw, annotate and arrange complex heatmaps. This might be very useful in genomic fields.<\/p>\n<\/div>\n<\/div>\n<p><!--end rdoc--><\/p>\n","protected":false},"excerpt":{"rendered":"<p>A heatmap is another way to visualize hierarchical clustering. It&#8217;s also called a false colored image, where data values are transformed to color scale.  Here, we&#8217;ll demonstrate how to draw and arrange a heatmap in R.<\/p>\n","protected":false},"author":1,"featured_media":7935,"parent":0,"menu_order":6,"comment_status":"open","ping_status":"closed","template":"","class_list":["post-7693","dt_lessons","type-dt_lessons","status-publish","has-post-thumbnail","hentry"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v25.2 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Heatmap in R: Static and Interactive Visualization - Datanovia<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.datanovia.com\/en\/lessons\/heatmap-in-r-static-and-interactive-visualization\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Heatmap in R: Static and Interactive Visualization - Datanovia\" \/>\n<meta property=\"og:description\" content=\"A heatmap is another way to visualize hierarchical clustering. It&#039;s also called a false colored image, where data values are transformed to color scale. Here, we&#039;ll demonstrate how to draw and arrange a heatmap in R.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.datanovia.com\/en\/lessons\/heatmap-in-r-static-and-interactive-visualization\/\" \/>\n<meta property=\"og:site_name\" content=\"Datanovia\" \/>\n<meta property=\"article:modified_time\" content=\"2020-04-25T22:17:07+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.datanovia.com\/en\/wp-content\/uploads\/2018\/10\/Couche_de_Soleil_sur_le_Sauveterre.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1024\" \/>\n\t<meta property=\"og:image:height\" content=\"512\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data1\" content=\"12 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\/\/www.datanovia.com\/en\/lessons\/heatmap-in-r-static-and-interactive-visualization\/\",\"url\":\"https:\/\/www.datanovia.com\/en\/lessons\/heatmap-in-r-static-and-interactive-visualization\/\",\"name\":\"Heatmap in R: Static and Interactive Visualization - Datanovia\",\"isPartOf\":{\"@id\":\"https:\/\/www.datanovia.com\/en\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/www.datanovia.com\/en\/lessons\/heatmap-in-r-static-and-interactive-visualization\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/www.datanovia.com\/en\/lessons\/heatmap-in-r-static-and-interactive-visualization\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/www.datanovia.com\/en\/wp-content\/uploads\/2018\/10\/Couche_de_Soleil_sur_le_Sauveterre.jpg\",\"datePublished\":\"2018-10-18T21:08:01+00:00\",\"dateModified\":\"2020-04-25T22:17:07+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/www.datanovia.com\/en\/lessons\/heatmap-in-r-static-and-interactive-visualization\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.datanovia.com\/en\/lessons\/heatmap-in-r-static-and-interactive-visualization\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.datanovia.com\/en\/lessons\/heatmap-in-r-static-and-interactive-visualization\/#primaryimage\",\"url\":\"https:\/\/www.datanovia.com\/en\/wp-content\/uploads\/2018\/10\/Couche_de_Soleil_sur_le_Sauveterre.jpg\",\"contentUrl\":\"https:\/\/www.datanovia.com\/en\/wp-content\/uploads\/2018\/10\/Couche_de_Soleil_sur_le_Sauveterre.jpg\",\"width\":1024,\"height\":512},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.datanovia.com\/en\/lessons\/heatmap-in-r-static-and-interactive-visualization\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/www.datanovia.com\/en\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Lessons\",\"item\":\"https:\/\/www.datanovia.com\/en\/lessons\/\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"Heatmap in R: Static and Interactive Visualization\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.datanovia.com\/en\/#website\",\"url\":\"https:\/\/www.datanovia.com\/en\/\",\"name\":\"Datanovia\",\"description\":\"Data Mining and Statistics for Decision Support\",\"publisher\":{\"@id\":\"https:\/\/www.datanovia.com\/en\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/www.datanovia.com\/en\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/www.datanovia.com\/en\/#organization\",\"name\":\"Datanovia\",\"url\":\"https:\/\/www.datanovia.com\/en\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.datanovia.com\/en\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/www.datanovia.com\/en\/wp-content\/uploads\/2018\/09\/datanovia-logo.png\",\"contentUrl\":\"https:\/\/www.datanovia.com\/en\/wp-content\/uploads\/2018\/09\/datanovia-logo.png\",\"width\":98,\"height\":99,\"caption\":\"Datanovia\"},\"image\":{\"@id\":\"https:\/\/www.datanovia.com\/en\/#\/schema\/logo\/image\/\"}}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Heatmap in R: Static and Interactive Visualization - Datanovia","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.datanovia.com\/en\/lessons\/heatmap-in-r-static-and-interactive-visualization\/","og_locale":"en_US","og_type":"article","og_title":"Heatmap in R: Static and Interactive Visualization - Datanovia","og_description":"A heatmap is another way to visualize hierarchical clustering. It's also called a false colored image, where data values are transformed to color scale. Here, we'll demonstrate how to draw and arrange a heatmap in R.","og_url":"https:\/\/www.datanovia.com\/en\/lessons\/heatmap-in-r-static-and-interactive-visualization\/","og_site_name":"Datanovia","article_modified_time":"2020-04-25T22:17:07+00:00","og_image":[{"width":1024,"height":512,"url":"https:\/\/www.datanovia.com\/en\/wp-content\/uploads\/2018\/10\/Couche_de_Soleil_sur_le_Sauveterre.jpg","type":"image\/jpeg"}],"twitter_card":"summary_large_image","twitter_misc":{"Est. reading time":"12 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/www.datanovia.com\/en\/lessons\/heatmap-in-r-static-and-interactive-visualization\/","url":"https:\/\/www.datanovia.com\/en\/lessons\/heatmap-in-r-static-and-interactive-visualization\/","name":"Heatmap in R: Static and Interactive Visualization - Datanovia","isPartOf":{"@id":"https:\/\/www.datanovia.com\/en\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.datanovia.com\/en\/lessons\/heatmap-in-r-static-and-interactive-visualization\/#primaryimage"},"image":{"@id":"https:\/\/www.datanovia.com\/en\/lessons\/heatmap-in-r-static-and-interactive-visualization\/#primaryimage"},"thumbnailUrl":"https:\/\/www.datanovia.com\/en\/wp-content\/uploads\/2018\/10\/Couche_de_Soleil_sur_le_Sauveterre.jpg","datePublished":"2018-10-18T21:08:01+00:00","dateModified":"2020-04-25T22:17:07+00:00","breadcrumb":{"@id":"https:\/\/www.datanovia.com\/en\/lessons\/heatmap-in-r-static-and-interactive-visualization\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.datanovia.com\/en\/lessons\/heatmap-in-r-static-and-interactive-visualization\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.datanovia.com\/en\/lessons\/heatmap-in-r-static-and-interactive-visualization\/#primaryimage","url":"https:\/\/www.datanovia.com\/en\/wp-content\/uploads\/2018\/10\/Couche_de_Soleil_sur_le_Sauveterre.jpg","contentUrl":"https:\/\/www.datanovia.com\/en\/wp-content\/uploads\/2018\/10\/Couche_de_Soleil_sur_le_Sauveterre.jpg","width":1024,"height":512},{"@type":"BreadcrumbList","@id":"https:\/\/www.datanovia.com\/en\/lessons\/heatmap-in-r-static-and-interactive-visualization\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.datanovia.com\/en\/"},{"@type":"ListItem","position":2,"name":"Lessons","item":"https:\/\/www.datanovia.com\/en\/lessons\/"},{"@type":"ListItem","position":3,"name":"Heatmap in R: Static and Interactive Visualization"}]},{"@type":"WebSite","@id":"https:\/\/www.datanovia.com\/en\/#website","url":"https:\/\/www.datanovia.com\/en\/","name":"Datanovia","description":"Data Mining and Statistics for Decision Support","publisher":{"@id":"https:\/\/www.datanovia.com\/en\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.datanovia.com\/en\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/www.datanovia.com\/en\/#organization","name":"Datanovia","url":"https:\/\/www.datanovia.com\/en\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.datanovia.com\/en\/#\/schema\/logo\/image\/","url":"https:\/\/www.datanovia.com\/en\/wp-content\/uploads\/2018\/09\/datanovia-logo.png","contentUrl":"https:\/\/www.datanovia.com\/en\/wp-content\/uploads\/2018\/09\/datanovia-logo.png","width":98,"height":99,"caption":"Datanovia"},"image":{"@id":"https:\/\/www.datanovia.com\/en\/#\/schema\/logo\/image\/"}}]}},"multi-rating":{"mr_rating_results":[]},"_links":{"self":[{"href":"https:\/\/www.datanovia.com\/en\/wp-json\/wp\/v2\/dt_lessons\/7693","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.datanovia.com\/en\/wp-json\/wp\/v2\/dt_lessons"}],"about":[{"href":"https:\/\/www.datanovia.com\/en\/wp-json\/wp\/v2\/types\/dt_lessons"}],"author":[{"embeddable":true,"href":"https:\/\/www.datanovia.com\/en\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.datanovia.com\/en\/wp-json\/wp\/v2\/comments?post=7693"}],"version-history":[{"count":2,"href":"https:\/\/www.datanovia.com\/en\/wp-json\/wp\/v2\/dt_lessons\/7693\/revisions"}],"predecessor-version":[{"id":15887,"href":"https:\/\/www.datanovia.com\/en\/wp-json\/wp\/v2\/dt_lessons\/7693\/revisions\/15887"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.datanovia.com\/en\/wp-json\/wp\/v2\/media\/7935"}],"wp:attachment":[{"href":"https:\/\/www.datanovia.com\/en\/wp-json\/wp\/v2\/media?parent=7693"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}