How to add text in a heatmap cell annotations using seaborn in Python?

Heatmaps are powerful data visualization tools that display the magnitude of phenomena using color intensity in a two-dimensional format. Seaborn provides excellent functionality for creating heatmaps and customizing cell annotations with text labels or numerical values to enhance data understanding.

Understanding Heatmaps

A heatmap visualizes data through colors in a matrix format, where different color intensities represent varying data values. The visual representation makes it easy to identify patterns, correlations, and outliers in datasets.

Basic Heatmap Syntax

The sns.heatmap() function provides comprehensive options for customization ?

sns.heatmap(data, *, annot=None, fmt='.2g', annot_kws=None, 
            linewidths=0, linecolor='white', cmap=None, center=None, 
            vmin=None, vmax=None, cbar=True)

Key Parameters for Text Annotations

Parameter Description
annot If True, writes data values in each cell. Can also accept a 2D array of custom text
fmt String formatting code for annotations. Use empty string "" for text annotations
annot_kws Dictionary of keyword arguments passed to matplotlib text function for styling

Method 1: Adding Custom Text Annotations

Create a heatmap with custom text labels using a 2D array of strings ?

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

# Creating sample data
data = np.array([[85, 92, 78, 91, 88], 
                 [76, 89, 94, 82, 87], 
                 [91, 85, 79, 93, 90]])

# Creating custom text annotations
text_labels = np.array([['A+', 'A+', 'B+', 'A+', 'B+'], 
                        ['B+', 'B+', 'A+', 'B+', 'B+'],
                        ['A+', 'A+', 'B+', 'A+', 'A+']])

# Creating heatmap with text annotations
plt.figure(figsize=(8, 4))
sns.heatmap(data, annot=text_labels, fmt='', cmap='Blues', 
            cbar_kws={'label': 'Scores'})
plt.title('Student Performance Heatmap')
plt.xlabel('Subjects')
plt.ylabel('Students')
plt.show()

Method 2: Combining Values and Custom Text

Display both numerical values and custom formatting using string templates ?

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

# Sample sales data
sales_data = np.array([[120, 85, 95, 110], 
                       [95, 140, 75, 88], 
                       [105, 92, 125, 98]])

# Create formatted text combining values and units
formatted_text = np.array([['$120K', '$85K', '$95K', '$110K'], 
                           ['$95K', '$140K', '$75K', '$88K'],
                           ['$105K', '$92K', '$125K', '$98K']])

plt.figure(figsize=(8, 5))
sns.heatmap(sales_data, annot=formatted_text, fmt='', 
            cmap='RdYlGn', linewidths=0.5, linecolor='white')
plt.title('Quarterly Sales Performance ($K)')
plt.xlabel('Quarters')
plt.ylabel('Sales Teams')
plt.show()

Method 3: Styling Text Annotations

Customize text appearance using the annot_kws parameter ?

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

# Rating data
ratings = np.array([[4.2, 3.8, 4.5, 4.1], 
                    [3.9, 4.3, 3.7, 4.0], 
                    [4.4, 4.1, 4.6, 4.2]])

# Star ratings text
star_text = np.array([['?????', '?????', '?????', '?????'], 
                      ['?????', '?????', '?????', '?????'],
                      ['?????', '?????', '?????', '?????']])

plt.figure(figsize=(8, 5))
sns.heatmap(ratings, annot=star_text, fmt='', 
            cmap='YlOrRd', 
            annot_kws={'fontsize': 12, 'color': 'darkblue', 'weight': 'bold'},
            linewidths=1, linecolor='gray')
plt.title('Product Ratings Heatmap')
plt.xlabel('Products')
plt.ylabel('Categories')
plt.show()

Best Practices

  • Use meaningful text ? Choose descriptive labels that add value to data interpretation
  • Keep text concise ? Avoid overly long text that might overlap or become unreadable
  • Consider contrast ? Ensure text color contrasts well with the heatmap colors
  • Format consistently ? Use uniform formatting across all annotations

Conclusion

Adding text annotations to heatmap cells enhances data interpretation by providing context and meaning beyond numerical values. Use the annot parameter with custom text arrays and fmt="" to display meaningful labels, and leverage annot_kws for styling customizations.

Updated on: 2026-03-27T07:02:19+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements