Plotting A 2D Heatmap Using Matplotlib In Python
Illustration
This tutorial is based on plotting a 2-D heatmap using matplotlib in Python programming. A heatmap can be plotted using various methods, but here in this tutorial, we are going to focus on constructing a heatmap using matplotlib.
Heatmap
A heatmap is a data visualization technique. A heatmap looks at the correlation values and converts them into colors in 2-dimensions. It interprets numbers very simply, it is used to simplify matrices of extremely higher order to find the relationship between vast numbers of variables in a matrix graphically.
Matplotlib
Matplotlib is a library in Python which is extremely useful in plotting various numbers of graphical plots for creating a relationship between various data structures.
Method to import matplotlib into the code space
import matplotlib.pyplot as plt # or from matplotlib import pyplot as plt
Algorithm
Step 1:
The first step is importing the matplotlib library to the code space as mentioned above.
Step 2:
The second step is importing the NumPy library to the code space as mentioned below.
import numpy as np
The need for the NumPy library is to fetch data in the form of an array with a particular shape but arbitrary values, so that a heatmap is created for this data. An example of such data structure is given below:
import numpy as np value=np.random.rand(5,5) value
output:
Step 3:
We use plt.imshow()
method to plot the heatmap.
plt.imshow(value,cmap='magma') # Here 'magma' is one of the styles of colormap in matplotlib.
Step 4:
The final step is to view the heatmap in the output section using the plt.show()
method.
plt.show()
The complete code for reference is mentioned below
from matplotlib import pyplot as plt import numpy as np value=np.random.rand(5,5) plt.imshow(value,cmap='magma') plt.title("Heatmap") plt.show()
Output:
Leave a Reply