View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Heatmap in Python: Methods, Types and Uses

By Rohit Sharma

Updated on Jul 03, 2025 | 12 min read | 16.02K+ views

Share:

Did you know?

In January 2025, Plotly released version 6.0.0, adding a powerful new feature for heatmaps—subtitles! This allows you to add clear, informative subtitles directly to your heatmap visualizations, making your data easier to understand! 

A heatmap in Python is a color-based chart that helps you quickly spot patterns, correlations, or outliers in a 2D dataset. You can create one using simple tools like seaborn.heatmap() or matplotlib.pyplot.imshow() depending on your data and need for customization. 

You’ve probably seen one in action, like when tracking clicks on a webpage to see which sections get the most attention. But figuring out how to create one, choose the right method, or customize it can feel confusing. 

This guide walks you through each step, so you can build heatmaps in Python that make your data easier to read and act on.

Improve your coding skills with upGrad’s online software engineering courses. Specialize in cybersecurity, full-stack development, and much more. Take the next step in your learning journey!

What is a Heatmap in Python? Methods and Examples

Heatmaps are everywhere, from weather reports to website analytics. In fact, companies like Hotjar use heatmaps to show where users click, scroll, or drop off on a page, helping businesses improve user experience instantly.

Handling heatmaps and managing large datasets isn’t just about plotting charts. You need the right tools and techniques to optimize, customize, and interact with your data. Here are three programs that can help you:

In Python, a heatmap is a 2D data chart where color shows the value of each cell. Darker shades usually mean higher values. You might use it to see the correlation between variables in a dataset or highlight sales performance by region.

Let’s break down what it is and how you can create one in Python:

Method 1: Creating a Heatmap with Seaborn’s heatmap()

Seaborn is built on top of Matplotlib and provides an easy-to-use interface for creating beautiful visualizations. The heatmap() function is one of its most popular features and allows you to display a matrix of data as a color-coded grid.

Step 1: Install and Import Libraries

To get started, make sure you have Seaborn installed. You can install it via pip if you haven’t already: 

pip install seaborn

Now, let's import the necessary libraries.

import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

Also Read: Top 32+ Python Libraries for Machine Learning Projects in 2025

Step 2: Prepare the Dataset

We’ll use a simple dataset for this example: the Iris dataset. This dataset contains measurements of four features (sepal length, sepal width, petal length, and petal width) across three species of iris flowers.

Let’s load the dataset and prepare a correlation matrix, which will be used to generate the heatmap.

# Load the Iris dataset from Seaborn
iris = sns.load_dataset('iris')

# Calculate the correlation matrix
correlation_matrix = iris.corr()

print(correlation_matrix)

This will give us a matrix showing how the features in the dataset are correlated with each other.

Step 3: Create the Basic Heatmap

Now, we’ll create a simple heatmap in Python from the correlation matrix using seaborn.heatmap(). Here's how: 

# Create a basic heatmap
sns.heatmap(correlation_matrix)
plt.title("Correlation Matrix of Iris Features")
plt.show()

Output:

This code generates a basic heatmap, where each cell’s color represents the magnitude of the correlation between the corresponding variables. By default, Seaborn will use a blue color palette to represent the data.

Step 4: Customize the Heatmap

You can customize the heatmap in Python to make it more readable and visually appealing. For example, you can adjust the color palette, add annotations, and change the font size to fit your needs. Let’s customize it using the 'viridis' color palette and other tweaks.

# Create a heatmap with customizations
sns.heatmap(correlation_matrix, annot=True, cmap='viridis', fmt='.2f', annot_kws={"size": 12}, linewidths=1, linecolor='black')
plt.title("Customized Correlation Matrix of Iris Features")
plt.show()

Output:

background

Liverpool John Moores University

MS in Data Science

Dual Credentials

Master's Degree17 Months

Placement Assistance

Certification6 Months

Explanation:

  • annot=True: Adds the correlation values inside the heatmap cells.
  • cmap='viridis': Sets the color palette to a yellow-to-purple scale for better contrast.
  • fmt='.2f': Formats the numbers to two decimal places.
  • annot_kws={"size": 12}: Sets the font size for the annotations inside each cell.
  • linewidths=1: Adds grid lines between cells to make them more distinct.
  • linecolor='black': Sets the grid lines to black, making them more visible.

When to Use?

  • Quick Visualizations: When you need a fast, visually appealing way to show data relationships, especially for correlation matrices.
  • Small to Medium Datasets: Ideal for datasets with a manageable number of features, where the correlations between them need to be visualized clearly.
  • Exploratory Data Analysis (EDA): Perfect for the initial steps in data analysis to identify patterns, trends, or outliers.
  • Customizable Visuals: Use it when you want to customize the appearance, such as choosing specific color palettes, adding annotations, or adjusting layout.
  • Heatmap with Annotations: When you want to display the actual correlation values inside the heatmap in Python for better interpretation.

Ready to start coding? Enroll in the Basic Python Programming course by upGrad, and in just 12 hours, you'll learn the fundamentals of Python, solve practical problems, and earn a certificate. Start today!

While seaborn.heatmap() is excellent for these use cases, let's now explore Matplotlib's imshow() method, which gives you more control over how the heatmap in Python is rendered, especially for larger or more complex datasets.

Method 2: Creating a Heatmap with Matplotlib’s imshow()

Matplotlib is listed as a dependency in several NASA-affiliated data science competitions and notebooks, such as the NASA Pose Bowl benchmark. This highlights its power in code execution environments and data exploration, making it an essential tool for analyzing complex datasets, even in high-stakes environments like space missions.

While Seaborn is perfect for quick and aesthetically pleasing visualizations, Matplotlib’s imshow() function gives you complete control over rendering. This method is ideal when you need to customize the grid further, fine-tune details, or work with more complex or large datasets. 

Step 1: Basic Setup

We’ll use the same correlation matrix we created earlier for consistency. 

import seaborn as sns
import matplotlib.pyplot as plt

# Load the Iris dataset from Seaborn
iris = sns.load_dataset('iris')

# Drop the 'species' column to keep only numerical values
iris_numeric = iris.drop(columns=['species'])

# Calculate the correlation matrix
correlation_matrix = iris_numeric.corr()

Step 2: Create a Heatmap Using imshow()

Now, let’s create a heatmap in Python using Matplotlib’s imshow() function. This method will display the data as a 2D grid and offer additional customization options.

# Create a heatmap using imshow
plt.figure(figsize=(8,6))
plt.imshow(correlation_matrix, cmap='viridis', interpolation='nearest')

# Add color bar to show the scale
plt.colorbar()

# Set the labels for the axes
plt.xticks(range(len(correlation_matrix.columns)), correlation_matrix.columns, rotation=45)
plt.yticks(range(len(correlation_matrix.columns)), correlation_matrix.columns)

plt.title("Correlation Matrix of Iris Features (Using imshow)")
plt.show()

Output:

Explanation:

  • imshow(correlation_matrix, cmap='viridis', interpolation='nearest'): This displays the heatmap. The viridis color palette is applied, and nearest interpolation ensures there’s no smoothing between data points.
  • plt.colorbar(): Adds a color bar to show the scale of the values.
  • plt.xticks() and plt.yticks(): These set the labels on both axes. rotation=45 rotates the x-axis labels for readability.
  • Customizations: You can adjust the colormap (cmap) to any palette you prefer and tweak the interpolation for a smoother or sharper grid appearance.

If you want to deepen your Python skills and apply them to fields like data analysis, finance, and engineering, enroll in upGrad’s DBA in Emerging Technologies with Concentration in Generative AI. Master the techniques behind intelligent, data-driven applications. Start today!

Method 3: Creating a Heatmap with Matplotlib’s pcolormesh()

Researchers and engineers use pcolormesh() to display evolving temperature fields, pollution dispersion, or weather patterns, allowing them to observe changes in real time as simulation data updates. 

This is particularly valuable in fields like meteorology, oceanography, and climate science, where the ability to update and visualize large, non-uniform grids is crucial for interpreting complex spatial data.

Unlike imshow(), Matplotlib’s pcolormesh() offers more flexibility with irregular grids and data points. It's perfect when you need to work with non-uniform data, providing precise control over the heatmap's layout and appearance. 

Step 1: Basic Setup

We'll use the same correlation matrix from the previous examples, but now we'll generate the heatmap in Python using pcolormesh().

import seaborn as sns
import matplotlib.pyplot as plt

# Load the Iris dataset from Seaborn
iris = sns.load_dataset('iris')

# Drop the 'species' column to keep only numerical values
iris_numeric = iris.drop(columns=['species'])

# Calculate the correlation matrix
correlation_matrix = iris_numeric.corr()

Step 2: Create the Heatmap Using pcolormesh()

Now, let's use pcolormesh() to generate a heatmap.

# Create a heatmap using pcolormesh
plt.figure(figsize=(8,6))
plt.pcolormesh(correlation_matrix, cmap='viridis', shading='auto')

# Add color bar to show the scale
plt.colorbar()

# Set the labels for the axes
plt.xticks(range(1, len(correlation_matrix.columns)+1), correlation_matrix.columns, rotation=45)
plt.yticks(range(1, len(correlation_matrix.columns)+1), correlation_matrix.columns)

plt.title("Correlation Matrix of Iris Features (Using pcolormesh)")
plt.show()

Output:

Explanation:

  • pcolormesh(correlation_matrix, cmap='viridis', shading='auto'): This function creates the heatmap. The viridis color palette is applied, and shading='auto' ensures that the grid cells are appropriately sized to fit the data.
  • plt.colorbar(): Adds a color bar to display the scale of the values.
  • plt.xticks() and plt.yticks(): These set the labels on both axes. The rotation=45 rotates the x-axis labels for better readability. 

Also Read: 10 Must-Know Data Visualization Tips for Beginners in 2025

Method 4: Creating an Interactive Heatmap with Plotly

Plotly Dash has been used to build dashboards that visualize live data from the HERA radio telescope array, enabling scientists to interactively explore and analyze large, complex datasets as they are collected. This capability to create interactive visualizations in real time makes Plotly an ideal tool for anyone looking to present data dynamically.

With Plotly, you can easily create interactive heatmaps, which are perfect for visualizing relationships in large datasets and enabling user engagement through zooming, hovering, and dynamic updates. 

Step 1: Install and Import Plotly

To get started with Plotly, you’ll first need to install it. You can install Plotly using pip: 

pip install plotly

Next, import the necessary libraries:

import plotly.express as px
import pandas as pd
import seaborn as sns

Step 2: Prepare the Dataset

We’ll use the same Iris dataset and calculate the correlation matrix, just like we did in the previous methods.

# Load the Iris dataset from Seaborn
iris = sns.load_dataset('iris')

# Drop the 'species' column to keep only numerical values
iris_numeric = iris.drop(columns=['species'])

# Calculate the correlation matrix
correlation_matrix = iris_numeric.corr()

Step 3: Create the Interactive Heatmap with Plotly

Plotly makes it super easy to create an interactive heatmap in Python with just a single line of code. Here’s how:

# Create an interactive heatmap using Plotly
fig = px.imshow(correlation_matrix, 
                color_continuous_scale='Viridis', 
                labels={'x': 'Features', 'y': 'Features'}, 
                title="Interactive Correlation Matrix of Iris Features")

# Show the heatmap
fig.show()

Output:

Explanation:

  • px.imshow(correlation_matrix): This creates the heatmap from the correlation matrix.
  • color_continuous_scale='Viridis': Sets the color palette to Viridis, a visually distinct color scale.
  • labels={'x': 'Features', 'y': 'Features'}: Adds labels for the x and y axes to make the heatmap clearer.
  • fig.show(): Displays the interactive heatmap, allowing you to zoom, pan, and hover for more detailed data.

Also Read: Pandas vs NumPy in Data Science: Top 15 Differences

To help you decide which method best suits your needs, here’s a comparison table that highlights the key differences in terms of use cases, flexibility, and interactivity:

Method

When to Use

Key Advantages

Best For

Seaborn heatmap() Quick, aesthetically pleasing visualizations, small/medium datasets Simple syntax, attractive visuals, easy to customize Exploratory Data Analysis (EDA), Correlation Matrices
Matplotlib imshow() When you need fine control over grid rendering and appearance Precise control over grid alignment and customizations Image-like data, scientific or performance-related visualizations
Matplotlib pcolormesh() Handling non-uniform data or larger, complex datasets Greater flexibility for irregular grids, fine grid control Geospatial data, temperature fields, large-scale datasets
Plotly imshow() Interactive, web-ready visualizations for presentations or dashboards Interactive features (zoom, hover), web integration Live data, web apps, presenting dynamic data

 

Struggling to create effective heatmaps for complex datasets? Check out upGrad’s Executive Programme in Generative AI for Leaders, where you’ll gain hands-on experience and learn how to apply them to solve complex real-life data challenges. Start today!

The method you choose can be influenced by the specific type of heatmap in Python you need to create, whether it’s for a correlation matrix, clustered data, or spatial patterns.

What are the Types of Heatmaps?

Heatmaps are versatile and can be used for various types of visualizations depending on the nature of your data. Each type serves a different purpose and can be created using the methods we've discussed so far.

Below are the three main types of heatmaps commonly used in Python:

1. Grid Heatmap

Grid heatmap in Python is the most common type, where values are represented in a matrix of rows and columns. The color intensity corresponds to the magnitude of the data, helping to easily identify patterns or trends.

When to Use:

  • When you want to visualize correlation matrices, performance metrics, or simple relationships between variables.
  • Best for small to medium datasets where the values are structured in a grid-like fashion.

Method to Use: Seaborn heatmap() or Matplotlib imshow() 

2. Clustered Heatmap

A clustered heatmap in Python uses hierarchical clustering to group similar data points or features together. This method is used when you want to understand how your data can be grouped based on similarities.

When to Use:

  • When you need to identify patterns or groupings within your data that might not be obvious at first glance.
  • Useful in fields like bioinformatics, market segmentation, and image analysis where relationships within the data are complex and non-linear.

Method to Use: Seaborn clustermap() 

3. Spatial Heatmap

Spatial heatmaps visualize data points across a physical space or geographic region. Each point is assigned a color based on its magnitude, and these heatmaps are usually overlaid on maps or images.

When to Use:

  • When you need to visualize spatial or geographical patterns. This is useful for analyzing location-based data like traffic patterns, customer behavior, or environmental data.
  • Great for working with large datasets that involve mapping values to geographical locations.

Method to Use: Matplotlib pcolormesh() or Plotly imshow() for interactive maps

Start experimenting with different datasets to strengthen your understanding and use color palettes wisely to make your visuals more readable. For more engaging presentations, explore interactive heatmaps in Plotly. Don’t forget to normalize your data for better clarity.

Check out upGrad’s LL.M. in AI and Emerging Technologies (Blended Learning Program), where you'll explore the intersection of law, technology, and AI, including how reinforcement learning is shaping the future of autonomous systems. Start today! 

Once you're comfortable, start exploring advanced topics such as clustering techniques for heatmaps. You can also work with geospatial visualizations using tools like Folium or Geopandas. Additionally, try applying machine learning models and visualizing their performance using heatmaps.

Advance Your Python Skills with upGrad!

From Seaborn’s simple heatmap() to Plotly’s interactive maps, these methods help visualize correlations, reveal patterns, and enhance interactivity for clearer insights.

However, as you work with larger datasets or more complex visualizations, you may face challenges in refining your approach.

To advance your heatmap skills, focus on mastering data normalization, color theory for better readability, and incorporating interactivity. For deeper growth in data science and visualization, upGrad’s courses in Python, data science, and machine learning can help you tackle more complex data visualizations and real-life projects.

In addition to the courses mentioned above, here are some more free courses that can help you enhance your skills:  

Feeling uncertain about your next step? Get personalized career counseling to identify the best opportunities for you. Visit upGrad’s offline centers for expert mentorship, hands-on workshops, and networking sessions to connect you with industry leaders!

Unlock the power of data with our popular Data Science courses, designed to make you proficient in analytics, machine learning, and big data!

Elevate your career by learning essential Data Science skills such as statistical modeling, big data processing, predictive analytics, and SQL!

Stay informed and inspired with our popular Data Science articles, offering expert insights, trends, and practical tips for aspiring data professionals!

References:
https://github.com/plotly/plotly.py/blob/main/CHANGELOG.md 
https://www.hotjar.com/heatmap-analysis/ 
https://drivendata.co/blog/nasa-pose-bowl-object-detection-benchmark 
https://stackoverflow.com/questions/15992149/how-to-update-pcolor-in-matplotlib 
https://plotly.com/examples/dashboards/

Frequently Asked Questions (FAQs)

1. Can heatmap in Python be used for real-time data visualization?

2. How can I create a heatmap in Python with categorical data?

3. Can I create a heatmap in Python for time-series data?

4. How do I handle missing values when creating a heatmap in Python?

5. Can a heatmap in Python be used for anomaly detection?

6. How do I optimize the performance of heatmaps in Python with large datasets?

7. Can I animate a heatmap in Python?

8. Can I combine heatmaps with other types of plots in Python?

9. How do I choose the right color palette for a heatmap in Python?

10. Can I create a 3D heatmap in Python?

11. How can I display a heatmap in Python on a geographical map?

Rohit Sharma

763 articles published

Rohit Sharma shares insights, skill building advice, and practical tips tailored for professionals aiming to achieve their career goals.

Get Free Consultation

+91

By submitting, I accept the T&C and
Privacy Policy

Start Your Career in Data Science Today

Top Resources

Recommended Programs

upGrad Logo

Certification

3 Months

Liverpool John Moores University Logo
bestseller

Liverpool John Moores University

MS in Data Science

Dual Credentials

Master's Degree

17 Months

IIIT Bangalore logo
bestseller

The International Institute of Information Technology, Bangalore

Executive Diploma in Data Science & AI

Placement Assistance

Executive PG Program

12 Months