Adding units to heatmap annotation in Seaborn

To add units to a heatmap annotation in Seaborn, we can customize the text annotations after creating the heatmap. This is useful for displaying data with specific units like percentages, currency, or measurements.

Steps to Add Units

  • Set the figure size and adjust the padding between and around the subplots.

  • Create a 5×5 dimension matrix using NumPy.

  • Plot rectangular data as a color-encoded matrix.

  • Annotate heatmap values with %age unit.

  • To display the figure, use show() method.

Example

Here's how to create a heatmap and add percentage units to the annotations ?

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

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

# Create sample data
data = np.random.rand(5, 5)

# Create heatmap with annotations
ax = sns.heatmap(data, annot=True, fmt='.1f', square=1, linewidth=1.)

# Add percentage unit to each annotation
for t in ax.texts: 
    t.set_text(t.get_text() + " %")

plt.show()

Adding Different Units

You can customize the units based on your data type ?

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

# Sample sales data
sales_data = np.random.randint(1000, 5000, (4, 3))

plt.figure(figsize=(8, 6))
ax = sns.heatmap(sales_data, annot=True, fmt='d', cmap='Blues')

# Add dollar sign for currency
for t in ax.texts:
    t.set_text("$" + t.get_text())

plt.title("Sales Data with Currency Units")
plt.show()

Custom Formatting Function

For more complex formatting, you can create a custom function ?

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

def format_with_units(value, unit="°C"):
    return f"{value:.1f}{unit}"

# Temperature data
temp_data = np.random.uniform(20, 35, (3, 4))

plt.figure(figsize=(8, 5))
ax = sns.heatmap(temp_data, annot=True, fmt='.1f', cmap='coolwarm')

# Apply custom formatting
for t in ax.texts:
    original_value = float(t.get_text())
    t.set_text(format_with_units(original_value, "°C"))

plt.title("Temperature Data with Units")
plt.show()

Conclusion

Adding units to heatmap annotations enhances data readability by providing context. Use the ax.texts property to iterate through annotations and modify them with appropriate units or formatting.

Updated on: 2026-03-25T22:01:14+05:30

711 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements