How to draw 2D Heatmap using Matplotlib in python?
Last Updated :
27 May, 2025
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
HeatmapSyntax
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 parameterExample 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 scaleExample 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 libraryExample 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 DatasetExample 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:
Heatmap using seabornUse 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.
Similar Reads
How to Draw 3D Cube using Matplotlib in Python?
In this article, we will deal with the 3d plots of cubes using matplotlib and Numpy. Cubes are one of the most basic of 3D shapes. A cube is a 3-dimensional solid object bounded by 6 identical square faces. The cube has 6-faces, 12-edges, and 8-corners. All faces are squares of the same size. The to
6 min read
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 Draw Shapes in Matplotlib with Python
Matplotlib provides a collection of classes and functions that allow you to draw and manipulate various shapes on your plots. Whether you're adding annotations, creating diagrams, or visualizing data, understanding how to use these tools effectively will enhance your ability to create compelling vis
2 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 Add Labels in a Plot using Python?
Prerequisites: Python Matplotlib In this article, we will discuss adding labels to the plot using Matplotlib in Python. But first, understand what are labels in a plot. The heading or sub-heading written at the vertical axis (say Y-axis) and the horizontal axis(say X-axis) improves the quality of u
3 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
How to Add Axes to a Figure in Matplotlib with Python?
Matplotlib is a library in Python used to create figures and provide tools for customizing it. It allows plotting different types of data, geometrical figures. In this article, we will see how to add axes to a figure in matplotlib. We can add axes to a figure in matplotlib by passing a list argument
2 min read
How to visualize data from MySQL database by using Matplotlib in Python ?
Prerequisites: Matplotlib in Python, MySQL While working with Python we need to work with databases, they may be of different types like MySQL, SQLite, NoSQL, etc. In this article, we will be looking forward to how to connect MySQL databases using MySQL Connector/Python. MySQL Connector module of Py
5 min read