Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • Pandas
  • Numpy
  • Seaborn
  • Ploty
  • Data visualization
  • Data Analysis
  • Power BI
  • Tableau
  • Machine Learning
  • Deep Learning
  • NLP
  • Computer Vision
  • Data Science for Beginners
  • Data Science interview questions
  • Data analysis interview questions
  • NLP Interview questions
Open In App
Next Article:
How to draw 2D Heatmap using Matplotlib in python?
Next article icon

How to draw 2D Heatmap using Matplotlib in python?

Last Updated : 27 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

A heatmap is a great tool for visualizing data across the surface. It highlights data that have a higher or lower concentration in the data distribution. A 2-D Heatmap is a data visualization tool that helps to represent the magnitude of the matrix in form of a colored table. In Python, we can plot 2-D Heatmaps using the Matplotlib and Seaborn packages. There are different methods to plot 2-D Heatmaps, some of which are discussed below. 

Let’s see an example: We will use the tips dataset which is an inbuilt dataset. This dataset contains information about restaurant tips, total bill amount, tip amount, customer details like sex and day of the week etc. Also, we will be using Seaborn and Matplotlib libraries for this.

Python
import seaborn as sns import matplotlib.pyplot as plt  df = sns.load_dataset("tips") heatmap_data = df.pivot_table(index="day", columns="sex", values="tip", aggfunc="mean") sns.heatmap(heatmap_data, annot=True, cmap="YlGnBu") plt.show() 

Output

heatmap
Heatmap

Syntax

seaborn.heatmap(data, vmin=None, vmax=None, cmap=None, annot=None, fmt='.2g', linewidths=0, linecolor='white', cbar=True, square=False, **kwargs)

Parameters:

  • data: Rectangular dataset (2D array, DataFrame, or similar) used to draw the heatmap.
  • vmin, vmax: Values to anchor the colormap, otherwise inferred from the data.
  • cmap: Colormap used to map data values to colors (e.g., "coolwarm", "YlGnBu").
  • annot: If True, write the data value in each cell; can also be a DataFrame of strings.
  • fmt: String formatting code to use when adding annotations.
  • linewidths: Width of the lines that will divide each cell.
  • linecolor: Color of the lines dividing the cells.
  • cbar: Boolean value to display the color bar.
  • square: If True, set the Axes aspect to “equal” so each cell will be square-shaped.

Returns: It returns a matplotlib Axes object with the heatmap drawn onto it.

Example 1- Different Colormaps in Heatmap Using Matplotlib

We can choose different colors for Heatmap using the cmap parameter. cmap can help us in making our heatmap more informative.

Python
# Program to plot 2-D Heat map # using matplotlib.pyplot.imshow() method import numpy as np import matplotlib.pyplot as plt  data = np.random.random((12, 12)) plt.imshow(data, cmap='autumn')  plt.title("Heatmap with different color") plt.show() 

Output:

heatmap with camp parameter
heatmap with camp parameter

Example 2- Adding Colorbar to Heatmap Using Matplotlib

We can add a colorbar to the heatmap using plt.colorbar(). colorbar shows the weight of color relatively between a certain range.

Python
data = np.random.random((12, 12)) plt.imshow(data, cmap='autumn', interpolation='nearest')  # Add colorbar plt.colorbar()  plt.title("Heatmap with color bar") plt.show() 

Output:

Heatmap with colorbar scale
Heatmap with colorbar scale

Example 3 - Customized Heatmap Using Matplotlib Library 

We can customize this heatmap using different functions and parameters to make it more informative and beautiful. we will use plt.annotate() to annotate values in the heatmap. Also, we will use colors library to customize the color of the heatmap. 

Python
import matplotlib.colors as colors  # Generate random data data = np.random.randint(0, 100, size=(8, 8))  # Create a custom color map  # with blue and green colors colors_list = ['#0099ff', '#33cc33'] cmap = colors.ListedColormap(colors_list)  # Plot the heatmap with custom colors and annotations plt.imshow(data, cmap=cmap, vmin=0,\            vmax=100, extent=[0, 8, 0, 8]) for i in range(8):     for j in range(8):         plt.annotate(str(data[i][j]), xy=(j+0.5, i+0.5),                      ha='center', va='center', color='white')  # Add colorbar cbar = plt.colorbar(ticks=[0, 50, 100]) cbar.ax.set_yticklabels(['Low', 'Medium', 'High'])  # Set plot title and axis labels plt.title("Customized heatmap with annotations") plt.xlabel("X-axis") plt.ylabel("Y-axis")  # Display the plot plt.show() 

Output:

advance customized heatmap using matplotlib library
advance customized heatmap using matplotlib library

Example 4- Correlation Matrix of a Dataset Using Heatmap

Next, we will use a heatmap to plot the correlation between columns of the dataset. We will use correlation to find the relation between columns of the dataset.

Python
import pandas as pd import matplotlib.pyplot as plt from matplotlib import colors  df = pd.read_csv("gold_price_data.csv")  # Calculate correlation between columns corr_matrix = df.corr()  # Create a custom color  # map with blue and green colors colors_list = ['#FF5733', '#FFC300'] cmap = colors.ListedColormap(colors_list)  # Plot the heatmap with custom colors and annotations plt.imshow(corr_matrix, cmap=cmap, vmin=0\            , vmax=1, extent=[0, 5, 0, 5]) for i in range(5):     for j in range(5):         plt.annotate(str(round(corr_matrix.values[i][j], 2)),\                      xy=(j+0.25, i+0.7),                      ha='center', va='center', color='white')  # Add colorbar cbar = plt.colorbar(ticks=[0, 0.5, 1]) cbar.ax.set_yticklabels(['Low', 'Medium', 'High'])  # Set plot title and axis labels plt.title("Correlation Matrix Of The Dataset") plt.xlabel("Features") plt.ylabel("Features")  # Set tick labels plt.xticks(range(len(corr_matrix.columns)),\            corr_matrix.columns, rotation=90) plt.yticks(range(len(corr_matrix.columns)),            corr_matrix.columns)  # Display the plot plt.show() 

Output:

Correlation Matrix of the Dataset
Correlation Matrix of the Dataset

Example 5- Heatmap Using Seaborn Library 

We can also use the Seaborn library to plot heatmaps even plotting heatmaps using Seaborn is comparatively easier than the matplotlib library. To plot the heatmap using Seaborn we will use sns.heatmap() function from the Seaborn library.

Python
# importing the modules import numpy as np import seaborn as sns import matplotlib.pyplot as plt    # generating 2-D 10x10 matrix of random numbers # from 1 to 100 data = np.random.randint(low=1,                          high=100,                          size=(10, 10))    # plotting the heatmap hm = sns.heatmap(data=data,                 annot=True)    # displaying the plotted heatmap plt.show() 

Output:

download
Heatmap using seaborn

Use Cases for Heatmaps 

As we know the Heatmap is just a colored representation of a matrix. However, heatmap has a very large use case. We can use heatmaps for the following purpose.

  •  It is used to see the correlation between columns of a dataset where we can use a darker color for columns having a high correlation. 
  •  We can also use heatmaps for plotting various time series and finance-related data where the Y-axis will be the month and X-axis will be the year and the element of the heatmap will be our data.

Next Article
How to draw 2D Heatmap using Matplotlib in python?

V

vanshgaur14866
Improve
Article Tags :
  • Technical Scripter
  • Python
  • Technical Scripter 2020
  • Python-matplotlib
Practice Tags :
  • python

Similar Reads

    How to reverse a Colormap using Matplotlib in Python?
    Prerequisites: Matplotlib Matplotlib has many built-in Colormaps. Colormaps are nothing but the dictionary which maps the integer data/numbers into colors. Colormaps are used to differentiate or distinguish the data in a particular plot. The reason to use the colormaps is that it is easier for human
    6 min read
    How to Plot Mfcc in Python Using Matplotlib?
    Mel-frequency cepstral coefficients (MFCC) are widely used in audio signal processing and speech recognition tasks. They represent the spectral characteristics of an audio signal and are commonly used as features for various machine-learning applications. In this article, we will explore how to comp
    2 min read
    How to Create Subplots in Matplotlib with Python?
    Matplotlib is a widely used data visualization library in Python that provides powerful tools for creating a variety of plots. One of the most useful features of Matplotlib is its ability to create multiple subplots within a single figure using the plt.subplots() method. This allows users to display
    6 min read
    How to import matplotlib in Python?
    Matplotlib is a Python library used to create different types of charts and graphs. It helps to turn data into visual formats like line charts, bar graphs and histograms. This makes it easier to understand and present your data. In this guide you’ll learn how to install and import Matplotlib in Pyth
    1 min read
    How to plot Andrews curves using Pandas in Python?
    Andrews curves are used for visualizing high-dimensional data by mapping each observation onto a function. It preserves means, distance, and variances. It is given by formula: T(n) = x_1/sqrt(2) + x_2 sin(n) + x_3 cos(n) + x_4 sin(2n) + x_5 cos(2n) + … Plotting Andrews curves on a graph can be done
    2 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.

What kind of Experience do you want to share?

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