Matplotlib Heatmap
Matplotlib is a powerful Python library used for creating visually appealing plots, charts, and graphs. It provides a wide range of plotting options, including heatmaps. Heatmaps are useful for visualizing large data sets or data distributions by displaying values in a two-dimensional color-coded grid. In this article, we will explore how to create heatmaps using the Matplotlib library.
Matplotlib Heatmap Prerequisites
Before we delve into creating a heatmap, make sure you have Matplotlib installed in your Python environment. If it’s not installed, you can use the following command to install it:
pip install matplotlib
Once installed, you can import it in your Python script using the following code:
import matplotlib.pyplot as plt
Creating a Basic Heatmap in Matplotlib
To create a basic heatmap using Matplotlib, we first need some data. Let’s consider a simple example where we have a 2D list of values representing temperatures in different cities over a week:
temperatures = [
[25, 27, 30, 28, 26, 24, 22],
[23, 26, 29, 27, 25, 24, 21],
[22, 25, 26, 28, 27, 25, 23],
[24, 27, 30, 29, 28, 25, 23],
[23, 26, 27, 28, 26, 25, 22]
]
To plot this data as a heatmap, we can use the imshow()
function provided by Matplotlib:
plt.imshow(temperatures)
plt.show()
Running this code will display the heatmap as a color-coded grid, with each cell representing a temperature value from the dataset. The color of each cell indicates the magnitude of the temperature value.
Customizing the Heatmap in Matplotlib
To enhance the visualization and make it more informative, we can customize various aspects of the heatmap.
Adding Colorbar
A colorbar is a useful addition to a heatmap as it provides a visual representation of the color-coding used in the plot. We can add a colorbar using the colorbar()
function:
plt.imshow(temperatures)
plt.colorbar()
plt.show()
This will display the colorbar alongside the heatmap, allowing us to infer the temperature range associated with each color.
Changing Colormap
By default, Matplotlib uses a colormap called ‘viridis’ to color the heatmap. However, we can choose from a wide range of predefined colormaps or even create custom colormaps. Let’s change the colormap to ‘hot’:
plt.imshow(temperatures, cmap='hot')
plt.colorbar()
plt.show()
This will change the color scheme of the heatmap to use warmer colors, with hotter temperatures appearing in bright red and cooler temperatures appearing in dark blue.
Adding Labels and Title
We can add labels to the x-axis, y-axis, and a title to the heatmap using the xlabel()
, ylabel()
, and title()
functions, respectively:
plt.imshow(temperatures, cmap='hot')
plt.colorbar()
plt.xlabel('Days')
plt.ylabel('Cities')
plt.title('Temperature Heatmap')
plt.show()
This will display the labels and title on the heatmap, enhancing its readability and providing context to the viewer.
Advanced Heatmap Customizations in Matplotlib
In addition to the basic customizations, Matplotlib provides several advanced customization options to make your heatmap more visually appealing and informative. Let’s explore a few examples.
Showing Values in Each Cell
We can display the actual values of each cell within the heatmap by adding text annotations using the text()
function. Let’s display the temperature values in each cell:
plt.imshow(temperatures, cmap='hot')
plt.colorbar()
for i in range(len(temperatures)):
for j in range(len(temperatures[0])):
plt.text(j, i, temperatures[i][j], ha='center', va='center', color='white')
plt.xlabel('Days')
plt.ylabel('Cities')
plt.title('Temperature Heatmap with Values')
plt.show()
This will display the temperature values in each cell, making it easier to interpret the heatmap.
Masking Certain Cells
Sometimes, we may want to focus on specific cells and mask the rest of the cells in the heatmap. We can achieve this by creating a masked array using the ma.masked_where()
function provided by the NumPy library:
import numpy as np
temperatures = np.array([
[25, 27, 30, 28, 26, 24, 22],
[23, 26, 29, 27, 25, 24, 21],
[22, 25, 26, 28, 27, 25, 23],
[24, 27, 30, 29, 28, 25, 23],
[23, 26, 27, 28, 26, 25, 22]
])
masked_temperatures = np.ma.masked_where(temperatures < 26, temperatures)
plt.imshow(masked_temperatures, cmap='hot')
plt.colorbar()
plt.show()
In this example, we have created a masked array where all the temperature values below 26 are hidden and appear as masked cells in the heatmap.
Changing Cell Size and Aspect Ratio
By default, Matplotlib assumes equal cell sizes and aspect ratios in a heatmap. However, we may want to adjust these parameters to provide a more accurate representation of the data. We can use the extent
parameter and the aspect
parameter of the imshow()
function to achieve this:
plt.imshow(temperatures, cmap='hot', extent=[0, 7, 0, 5], aspect='auto')
plt.colorbar()
plt.xlabel('Days')
plt.ylabel('Cities')
plt.title('Temperature Heatmap with Adjusted Cell Size')
plt.show()
In this example, we have set the extent
parameter to [0, 7, 0, 5]
, indicating the range of the x-axis and y-axis. We have also set the aspect
parameter to 'auto'
, which automatically adjusts the aspect ratio of the cells.
Matplotlib Heatmap Conclusion
In this article, we explored how to create heatmaps using the Matplotlib library in Python. We learned how to create a basic heatmap, customize its appearance, and implement advanced customizations such as adding labels, value annotations, colorbars, and masking specific cells. Heatmaps are a powerful tool for visualizing data distributions and patterns, and Matplotlib makes it easy to create visually appealing and informative heatmaps in Python.
Matplotlib Heatmap Code Examples:
- Basic Heatmap:
import matplotlib.pyplot as plt
temperatures = [
[25, 27, 30, 28, 26, 24, 22],
[23, 26, 29, 27, 25, 24, 21],
[22, 25, 26, 28, 27, 25, 23],
[24, 27, 30, 29, 28, 25, 23],
[23, 26, 27, 28, 26, 25, 22]
]
plt.imshow(temperatures)
plt.show()
Output:
- Heatmap with Colorbar:
import matplotlib.pyplot as plt
plt.imshow(temperatures)
plt.colorbar()
plt.show()
Output:
- Heatmap with ‘hot’ Colormap:
import matplotlib.pyplot as plt
plt.imshow(temperatures, cmap='hot')
plt.colorbar()
plt.show()
Output:
- Heatmap with Labels and Title:
import matplotlib.pyplot as plt
plt.imshow(temperatures, cmap='hot')
plt.colorbar()
plt.xlabel('Days')
plt.ylabel('Cities')
plt.title('Temperature Heatmap')
plt.show()
Output:
- Heatmap with Values:
import matplotlib.pyplot as plt
plt.imshow(temperatures, cmap='hot')
plt.colorbar()
for i in range(len(temperatures)):
for j in range(len(temperatures[0])):
plt.text(j, i, temperatures[i][j], ha='center', va='center', color='white')
plt.xlabel('Days')
plt.ylabel('Cities')
plt.title('Temperature Heatmap with Values')
plt.show()
Output:
- Masking Certain Cells:
import matplotlib.pyplot as plt
import numpy as np
temperatures = np.array([
[25, 27, 30, 28, 26, 24, 22],
[23, 26, 29, 27, 25, 24, 21],
[22, 25, 26, 28, 27, 25, 23],
[24, 27, 30, 29, 28, 25, 23],
[23, 26, 27, 28, 26, 25, 22]
])
masked_temperatures = np.ma.masked_where(temperatures < 26, temperatures)
plt.imshow(masked_temperatures, cmap='hot')
plt.colorbar()
plt.show()
Output:
- Heatmap with Adjusted Cell Size:
import matplotlib.pyplot as plt
plt.imshow(temperatures, cmap='hot', extent=[0, 7, 0, 5], aspect='auto')
plt.colorbar()
plt.xlabel('Days')
plt.ylabel('Cities')
plt.title('Temperature Heatmap with Adjusted Cell Size')
plt.show()
Output:
Note: The above examples assume that you have already imported matplotlib.pyplot
and assigned the temperature data to the temperatures
variable as shown in the previous sections. Make sure to adjust the code according to your data and requirements.
Now that you have a good understanding of creating heatmaps using Matplotlib, feel free to explore further and experiment with different data sets and customization options.