Customizing Heatmap Colors with Matplotlib

Matplotlib is a powerful and versatile library in Python for creating static, animated, and interactive visualizations. One of the most popular types of visualizations is the heatmap, which is used to represent data in a matrix format, where individual values are represented by colors. Customizing the colors in a heatmap can significantly enhance the readability and interpretability of the data. In this article, we will explore various techniques to customize colors in Matplotlib heatmaps.

Table of Content

  • Introduction to Heatmaps
  • Methods for Color Customization for Heatmap
  • Implementing Customizing Colors in Matplotlib for Heatmap
    • Method 1 : Using a Built-in Colormap (Viridis)
    • Method 2 : Creating a Custom Colormap
    • Method 3 : Adjusting Color Limits
    • Method 4 : Using Colorbars for Heatmap
    • Method 5 : Adding Labels and Titles
  • Advance Customization for Customizing Colors in Heatmap

Introduction to Heatmaps

Heatmaps are a graphical representation of data where individual values are represented as colors. They are particularly useful for visualizing the magnitude of values in a matrix format, making it easy to identify patterns, correlations, and outliers. Heatmaps are widely used in various fields, including data science, bioinformatics, finance, and more. Importance of Customizing Colors in Heatmaps:

  • Custom colors make it simple to see key points in the data.
  • Different color schemes and custom colors make the heatmap more attractive.
  • Changing color limits can highlight important patterns and trends.
  • Adding labels and titles makes the data clear.
  • Customizations make the heatmap engaging and easy to understand.

Methods for Color Customization for Heatmap

  • Built-in Colormaps: Matplotlib offers a range of ready-to-use colormaps like ‘viridis’, ‘plasma’, and ‘inferno’ that can be applied directly to the heatmap.
  • Creating Custom Colormaps: Users can define their own color schemes using the LinearSegmentedColormap class in Matplotlib, specifying colors and their positions to create a custom gradient.
  • Adjusting Color Limits: By setting custom minimum and maximum values (vmin and vmax), users can control the range of colors used in the heatmap, effectively highlighting specific data ranges.
  • Using Colorbars: Adding colorbars alongside the heatmap provides a visual scale for interpreting the data, enhancing its clarity.
  • Adding Labels and Titles: Include labels for axes and a title for the heatmap further aids interpretation, ensuring that viewers understand the context of the displayed data.

Implementing Customizing Colors in Matplotlib for Heatmap

Step 1: Importing Libraries and Generating Data

  • We import necessary libraries: Matplotlib for plotting, NumPy for numerical operations, and LinearSegmentedColormap for creating custom colormaps.
  • A 10×10 matrix of random values between 0 and 1 is generated as our data for the heatmap.
Python
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import LinearSegmentedColormap

# Generating some random data
data = np.random.rand(10, 10)


Step 2:Visualization Customizing Colors in Matplotlib

Method 1 : Using a Built-in Colormap (Viridis)

  • Divides the figure into a 2×3 grid of subplots and selects the first subplot.
  • Creates a heatmap using the ‘viridis’ colormap, displaying the random data.
  • Adds a colorbar to the plot, providing a visual scale for the colormap.
  • Sets the title of the subplot to indicate the use of the ‘viridis’ colormap.
Python
# Method 1: Using a Built-in Colormap (Viridis)
plt.subplot(231)
plt.imshow(data, cmap='viridis')
plt.colorbar()
plt.title('Built-in Colormap: Viridis')
plt.show()

Output:

Built-in color plot

Method 2 : Creating a Custom Colormap

  • Defines a list of custom colors to create the colormap.
  • Creates a custom colormap using the LinearSegmentedColormap.from_list method, which interpolates colors between the defined values.
  • Selects the second subplot.
  • Creates a heatmap using the custom colormap.
  • Sets the title of the subplot to indicate the use of a custom colormap.
Python
# Method 2: Creating a Custom Colormap
colors = ["#ff0000", "#ffff00", "#00ff00", "#00ffff", "#0000ff"]  # Define custom colors
custom_cmap = LinearSegmentedColormap.from_list("custom_cmap", colors)  # Create custom colormap
plt.subplot(232)
plt.imshow(data, cmap=custom_cmap)
plt.colorbar()
plt.title('Custom Colormap')
plt.show()

Output:

Custom color plot

Method 3 : Adjusting Color Limits

  • Selects the third subplot.
  • Creates a heatmap using the ‘viridis’ colormap with custom color limits (vmin and vmax) set to highlight values between 0.3 and 0.7.
  • Sets the title of the subplot to indicate the custom color limits.
Python
# Method 3: Adjusting Color Limits
plt.subplot(233)
plt.imshow(data, cmap='viridis', vmin=0.3, vmax=0.7)
plt.colorbar()
plt.title('Color Limits: 0.3 to 0.7')
plt.show()

Output:

Custom limit plot

Method 4 : Using Colorbars for Heatmap

  • Selects the fourth subplot.
  • Creates a heatmap using the ‘plasma’ colormap and stores the returned image object.
  • Adds a horizontal colorbar to the plot, associated with the heatmap.
  • Sets the title of the subplot to indicate the presence of a colorbar.
Python
# Method 4: Using Colorbars
plt.subplot(234)
img = plt.imshow(data, cmap='plasma')
plt.colorbar(img, orientation='horizontal')
plt.title('Colorbar')
plt.show()

Output:

Custom colorbar plot

Method 5 : Adding Labels and Titles

  • Selects the fifth subplot.
  • Creates a heatmap using the ‘inferno’ colormap.
  • Sets the title of the subplot to indicate the presence of labels.
  • Adds a label to the X-axis.
  • Adds a label to the Y-axis.
Python
# Method 5: Adding Labels and Titles
plt.subplot(235)
plt.imshow(data, cmap='inferno')
plt.colorbar()
plt.title('Heatmap with Labels')
plt.xlabel('X Axis')
plt.ylabel('Y Axis')
plt.show()

Output:

Adding labels to plot

Advance Customization for Customizing Colors in Heatmap

We pivot the dataset to create a matrix format suitable for creating a heatmap. This helps to organize the data based on months and years. Define a custom colormap with a list of custom colors using LinearSegmentedColormap. This custom colormap will be used to color the heatmap.

  • Determine the minimum and maximum values in the dataset to set the color limits for the heatmap accordingly.
  • Use Matplotlib’s imshow function to create the heatmap using the pivoted dataset, custom colormap, and adjusted color limits.
  • Add a colorbar to the plot to provide a visual scale for interpreting the colors in the heatmap.
  • Also add labels for the x-axis (Year), y-axis (Month), and a title to provide context to the heatmap.
  • Customize the tick labels for both the x-axis and y-axis to match the dataset.
  • We add annotations to each cell of the heatmap to display the exact number of passengers for each month and year.

Customize the appearance of the grid lines in the heatmap. Set a logarithmic scale for the colorbar to better visualize the data distribution.

Finally, we display the plot with all the customizations applied.

Python
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib.colors import LinearSegmentedColormap

# Load a sample dataset from Seaborn
data = sns.load_dataset("flights")

# Pivot the dataset to create a matrix
data_pivot = data.pivot(index="month", columns="year", values="passengers")

# Create a custom colormap
colors = ["#ffffcc", "#a1dab4", "#41b6c4", "#2c7fb8", "#253494"]  # Define custom colors
custom_cmap = LinearSegmentedColormap.from_list("custom_cmap", colors)  # Create custom colormap

# Adjust color limits
vmin = data_pivot.min().min()  # Minimum value in the dataset
vmax = data_pivot.max().max()  # Maximum value in the dataset

# Create the heatmap
plt.imshow(data_pivot, cmap=custom_cmap, vmin=vmin, vmax=vmax)

# Add colorbar
cbar = plt.colorbar(label='Passengers')

# Add labels and title
plt.title('Passenger Flights')
plt.xlabel('Year')
plt.ylabel('Month')

# Customize tick labels
plt.xticks(range(len(data_pivot.columns)), data_pivot.columns, rotation=45)
plt.yticks(range(len(data_pivot.index)), data_pivot.index)

# Add annotations
for i in range(len(data_pivot.index)):
    for j in range(len(data_pivot.columns)):
        plt.text(j, i, data_pivot.iloc[i, j], ha="center", va="center", color="black")

# Customize grid appearance
plt.grid(color='gray', linestyle='--', linewidth=0.5)

# Set logarithmic scale for the colorbar
cbar.ax.set_yscale('log')

# Display the plot
plt.show()

Output:

Advance Plot

Conclusion

Customizing colors in Matplotlib heatmaps can greatly enhance the visual appeal and interpretability of your data visualizations. By choosing appropriate colormaps, creating custom colormaps, and adding informative colorbars and annotations, you can create heatmaps that effectively communicate your data insights. Whether you are working with correlation matrices, gene expression data, or any other type of matrix data, these techniques will help you create compelling and informative heatmaps.



Contact Us