Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • GfG 160: Daily DSA
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Data Visualization
  • Statistics in R
  • Machine Learning in R
  • Data Science in R
  • Packages in R
  • Data Types
  • String
  • Array
  • Vector
  • Lists
  • Matrices
  • Oops in R
Open In App
Next Article:
Create a Heatmap in R Programming - heatmap() Function
Next article icon

Create a Heatmap in R Programming - heatmap() Function

Last Updated : 26 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

A heatmap() function in R Programming Language is used to plot a heatmap. A heatmap is defined as a graphical representation of data using colors to visualize the value of the matrix. In this to represent more common values or higher activities brighter colors reddish colors are used and to less common or activity values darker colors are preferred. Heatmap is also defined by the name of the shading matrix. 

R - heatmap() Function

Syntax: heatmap(data)

Parameters: 

  • data: It represent matrix data, such as values of rows and columns

Return: This function draws a heatmap. 

Create a Heatmap in R Programming Language

r
# Set seed for reproducibility
set.seed(110)

# Create example data
data <- matrix(rnorm(100, 0, 5), nrow = 10, ncol = 10)

# Column names
colnames(data) <- paste0("col", 1:10)
rownames(data) <- paste0("row", 1:10)

# Draw a heatmap
heatmap(data)        

Output: 


gh
Heatmap in R Programming


Here, in the above example number of rows and columns are specified to draw heatmap with a given function.

Create heatmap in R using colorRampPalette

r
# Set seed for reproducibility
set.seed(110)

# Create example data        
data <- matrix(rnorm(100, 0, 5), nrow = 10, ncol = 10)

# Column names    
colnames(data) <- paste0("col", 1:10)
rownames(data) <- paste0("row", 1:10)

# Remove dendrogram
# Manual color range
my_colors <- colorRampPalette(c("cyan", "darkgreen"))

# Heatmap with manual colors
heatmap(data, col = my_colors(100))                            

Output: 


ghh
Heatmap in R Programming


In the above example heat map is drawn by using colorRampPalette to merge two different colors.

Heatmap in R with Title and Axis Labels

R
# Set seed for reproducibility
set.seed(110)

# Create example data        
data <- matrix(rnorm(100, 0, 5), nrow = 10, ncol = 10)

# Column names    
colnames(data) <- paste0("col", 1:10)
rownames(data) <- paste0("row", 1:10)

# Remove dendrogram
# Manual color range
my_colors <- colorRampPalette(c("cyan", "darkgreen"))

# Heatmap with manual colors
heatmap(data, col = my_colors(100), main = "Customized Heatmap", 
        xlab = "Columns", ylab = "Rows")

Output:


gh
Heatmap in R Programming


Margins Around the Heatmap Plot

R
# Set seed for reproducibility
set.seed(110)

# Create example data        
data <- matrix(rnorm(100, 0, 5), nrow = 10, ncol = 10)

# Column names    
colnames(data) <- paste0("col", 1:10)
rownames(data) <- paste0("row", 1:10)

# Remove dendrogram
# Manual color range
my_colors <- colorRampPalette(c("cyan", "darkgreen"))

# Heatmap with margins around the plot
heatmap(data, col = my_colors(100), main = "Customized Heatmap", 
        xlab = "Columns", ylab = "Rows", margins = c(5, 10))

Output:


gh
Heatmap in R Programming


Heatmap in R without Dendrogram

R
# Set seed for reproducibility
set.seed(110)

# Create example data        
data <- matrix(rnorm(100, 0, 5), nrow = 10, ncol = 10)

# Column names    
colnames(data) <- paste0("col", 1:10)
rownames(data) <- paste0("row", 1:10)

# Remove dendrogram
# Manual color range
my_colors <- colorRampPalette(c("cyan", "darkgreen"))

# Heatmap with margins around the plot
heatmap(data, col = my_colors(100), main = "Customized Heatmap", 
        xlab = "Columns", ylab = "Rows", margins = c(5, 10),Colv = NA, Rowv = NA)

Output:


gh
Heatmap in R Programming


Conclusion

Creating a heatmap in R provides a powerful visual representation of data patterns, allowing for easy identification of trends, clusters, and variations. Through the flexibility of the heatmap function and additional customization options, users can tailor the appearance of the heatmap to effectively communicate insights.



Next Article
Create a Heatmap in R Programming - heatmap() Function

K

kaurbal1698
Improve
Article Tags :
  • R Language
  • R Graphics-Functions

Similar Reads

  • Create Dot Charts in R Programming - dotchart () Function
    dotchart() function in R Language is used to create a dot chart of the specified data. A dot chart is defined as a plot which is used to draw a Cleveland dot plot. Syntax: dotchart(x, labels = NULL, groups = NULL, gcolor = par("fg"), color = par("fg")) Parameters: x: it is defined as numeric vector
    2 min read
  • Melting and Casting in R Programming
    Melting and Casting are one of the interesting aspects in R programming to change the shape of the data and further, getting the desired shape. R programming language has many methods to reshape the data using reshape package. melt() and cast() are the functions that efficiently reshape the data. Th
    3 min read
  • Create a Plot Matrix of Scatterplots in R Programming - pairs() Function
    pairs() function in R language is used to return a plot matrix, consisting of scatter plots corresponding to each data frame. R - Create Plot Matrix of Scatterplots Syntax: pairs(data) Parameters:  data: It is defined as  value of pairs Plot. Returns: Color, Labels, Panels, and by Group in pairs plo
    2 min read
  • Convert a Data Frame into a Molten Form in R Programming - melt() Function
    function in R Language is used to combine multiple columns of s Data Frame into a single column. Syntax: melt(x, na.rm, value.name) Parameters: x: data to be melted na.rm: Boolean value to remove NA value.name: Setting column names Example 1: Python3 1== # R program to reshape data frame # Loading l
    2 min read
  • Convert an Object into a Matrix in R Programming - as.matrix() Function
    The as.matrix() function within R converts objects of various classes into a matrix. This can be helpful to work with structures of various data that can be converted into the matrix structure so that it becomes easier to analyze.Syntax: as.matrix(x)Parameters: x: Object to be convertedExample 1: Co
    2 min read
  • Plot Arrows Between Points in a Graph in R Programming - arrows() Function
    arrows() function in R Language is used to create arrows between the points on the graph specified. Syntax: arrows(x0, y0, x1, y1, length) Parameters: x0: represents x-coordinate of point from which to draw the arrow y0: represents y-coordinate of point from which to draw the arrow x1: represents x-
    2 min read
  • Addition of Lines to a Plot in R Programming - lines() Function
    In R, the lines() function is called to add on top of already existing plot. This is particularly helpful when you want to add more lines, such as trend lines, regression lines, or special lines, on a plot. The lines() function allows flexibility in line color, line width, and line type, with multip
    3 min read
  • Create Heatmap in R Using ggplot2
    A heatmap depicts the relationship between two attributes of a data frame as a color-coded tile. A heatmap produces a grid with multiple attributes of the data frame, representing the relationship between the two attributes taken at a time. In both data analysis and visualization, heatmaps are a com
    5 min read
  • Addition of more points to a Plot in R Programming - points() Function
    points() function in R Language is used to add a group of points of specified shapes, size and color to an existing plot. Syntax: points(x, y, cex, pch, col) Parameters: x, y: Vector of coordinates cex: size of points pch: shape of points col: color of points Sample Scatter Plot: Python3 1== # R pro
    2 min read
  • How to Create Correlation Heatmap in R
    In this article let's check out how to plot a Correlation Heatmap in R Programming Language. Analyzing data usually involves a detailed analysis of each feature and how it's correlated with each other. It's essential to find the strength of the relationship between each feature or in other words how
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

'); // $('.spinner-loading-overlay').show(); let script = document.createElement('script'); script.src = 'https://assets.geeksforgeeks.org/v2/editor-prod/static/js/bundle.min.js'; script.defer = true document.head.appendChild(script); script.onload = function() { suggestionModalEditor() //to add editor in suggestion modal if(loginData && loginData.premiumConsent){ personalNoteEditor() //to load editor in personal note } } script.onerror = function() { if($('.editorError').length){ $('.editorError').remove(); } var messageDiv = $('
').text('Editor not loaded due to some issues'); $('#suggestion-section-textarea').append(messageDiv); $('.suggest-bottom-btn').hide(); $('.suggestion-section').hide(); editorLoaded = false; } }); //suggestion modal editor function suggestionModalEditor(){ // editor params const params = { data: undefined, plugins: ["BOLD", "ITALIC", "UNDERLINE", "PREBLOCK"], } // loading editor try { suggestEditorInstance = new GFGEditorWrapper("suggestion-section-textarea", params, { appNode: true }) suggestEditorInstance._createEditor("") $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = true; } catch (error) { $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = false; } } //personal note editor function personalNoteEditor(){ // editor params const params = { data: undefined, plugins: ["UNDO", "REDO", "BOLD", "ITALIC", "NUMBERED_LIST", "BULLET_LIST", "TEXTALIGNMENTDROPDOWN"], placeholderText: "Description to be......", } // loading editor try { let notesEditorInstance = new GFGEditorWrapper("pn-editor", params, { appNode: true }) notesEditorInstance._createEditor(loginData&&loginData.user_personal_note?loginData.user_personal_note:"") $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = true; } catch (error) { $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = false; } } var lockedCasesHtml = `You can suggest the changes for now and it will be under 'My Suggestions' Tab on Write.

You will be notified via email once the article is available for improvement. Thank you for your valuable feedback!`; var badgesRequiredHtml = `It seems that you do not meet the eligibility criteria to create improvements for this article, as only users who have earned specific badges are permitted to do so.

However, you can still create improvements through the Pick for Improvement section.`; jQuery('.improve-header-sec-child').on('click', function(){ jQuery('.improve-modal--overlay').hide(); $('.improve-modal--suggestion').hide(); jQuery('#suggestion-modal-alert').hide(); }); $('.suggest-change_wrapper, .locked-status--impove-modal .improve-bottom-btn').on('click',function(){ // when suggest changes option is clicked $('.ContentEditable__root').text(""); $('.suggest-bottom-btn').html("Suggest changes"); $('.thank-you-message').css("display","none"); $('.improve-modal--improvement').hide(); $('.improve-modal--suggestion').show(); $('#suggestion-section-textarea').show(); jQuery('#suggestion-modal-alert').hide(); if(suggestEditorInstance !== null){ suggestEditorInstance.setEditorValue(""); } $('.suggestion-section').css('display', 'block'); jQuery('.suggest-bottom-btn').css("display","block"); }); $('.create-improvement_wrapper').on('click',function(){ // when create improvement option clicked then improvement reason will be shown if(loginData && loginData.isLoggedIn) { $('body').append('
'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.unlocked-status--improve-modal-content').css("display","none"); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { showErrorMessage(e.responseJSON,e.status) }, }); } else { if(loginData && !loginData.isLoggedIn) { $('.improve-modal--overlay').hide(); if ($('.header-main__wrapper').find('.header-main__signup.login-modal-btn').length) { $('.header-main__wrapper').find('.header-main__signup.login-modal-btn').click(); } return; } } }); $('.left-arrow-icon_wrapper').on('click',function(){ if($('.improve-modal--suggestion').is(":visible")) $('.improve-modal--suggestion').hide(); else{ } $('.improve-modal--improvement').show(); }); const showErrorMessage = (result,statusCode) => { if(!result) return; $('.spinner-loading-overlay:eq(0)').remove(); if(statusCode == 403) { $('.improve-modal--improve-content.error-message').html(result.message); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); return; } } function suggestionCall() { var editorValue = suggestEditorInstance.getValue(); var suggest_val = $(".ContentEditable__root").find("[data-lexical-text='true']").map(function() { return $(this).text().trim(); }).get().join(' '); suggest_val = suggest_val.replace(/\s+/g, ' ').trim(); var array_String= suggest_val.split(" ") //array of words var gCaptchaToken = $("#g-recaptcha-response-suggestion-form").val(); var error_msg = false; if(suggest_val != "" && array_String.length >=4){ if(editorValue.length { jQuery('.ContentEditable__root').focus(); jQuery('#suggestion-modal-alert').hide(); }, 3000); } } document.querySelector('.suggest-bottom-btn').addEventListener('click', function(){ jQuery('body').append('
'); jQuery('.spinner-loading-overlay').show(); if(loginData && loginData.isLoggedIn) { suggestionCall(); return; } // script for grecaptcha loaded in loginmodal.html and call function to set the token setGoogleRecaptcha(); }); $('.improvement-bottom-btn.create-improvement-btn').click(function() { //create improvement button is clicked $('body').append('
'); $('.spinner-loading-overlay').show(); // send this option via create-improvement-post api jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { showErrorMessage(e.responseJSON,e.status); }, }); });
"For an ad-free experience and exclusive features, subscribe to our Premium Plan!"
Continue without supporting
`; $('body').append(adBlockerModal); $('body').addClass('body-for-ad-blocker'); const modal = document.getElementById("adBlockerModal"); modal.style.display = "block"; } function handleAdBlockerClick(type){ if(type == 'disabled'){ window.location.reload(); } else if(type == 'info'){ document.getElementById("ad-blocker-div").style.display = "none"; document.getElementById("ad-blocker-info-div").style.display = "flex"; handleAdBlockerIconClick(0); } } var lastSelected= null; //Mapping of name and video URL with the index. const adBlockerVideoMap = [ ['Ad Block Plus','https://media.geeksforgeeks.org/auth-dashboard-uploads/abp-blocker-min.mp4'], ['Ad Block','https://media.geeksforgeeks.org/auth-dashboard-uploads/Ad-block-min.mp4'], ['uBlock Origin','https://media.geeksforgeeks.org/auth-dashboard-uploads/ub-blocke-min.mp4'], ['uBlock','https://media.geeksforgeeks.org/auth-dashboard-uploads/U-blocker-min.mp4'], ] function handleAdBlockerIconClick(currSelected){ const videocontainer = document.getElementById('ad-blocker-info-div-gif'); const videosource = document.getElementById('ad-blocker-info-div-gif-src'); if(lastSelected != null){ document.getElementById("ad-blocker-info-div-icons-"+lastSelected).style.backgroundColor = "white"; document.getElementById("ad-blocker-info-div-icons-"+lastSelected).style.borderColor = "#D6D6D6"; } document.getElementById("ad-blocker-info-div-icons-"+currSelected).style.backgroundColor = "#D9D9D9"; document.getElementById("ad-blocker-info-div-icons-"+currSelected).style.borderColor = "#848484"; document.getElementById('ad-blocker-info-div-name-span').innerHTML = adBlockerVideoMap[currSelected][0] videocontainer.pause(); videosource.setAttribute('src', adBlockerVideoMap[currSelected][1]); videocontainer.load(); videocontainer.play(); lastSelected = currSelected; }

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences