Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to annotate each cell of a heatmap in Seaborn?
To annotate each cell of a heatmap in Seaborn, we can set annot=True in the heatmap() method. This displays the actual data values inside each cell, making the heatmap more informative and easier to interpret.
Basic Heatmap with Annotations
Here's how to create a simple annotated heatmap ?
import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Set figure size
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
# Create sample data
data = pd.DataFrame(np.random.random((5, 5)),
columns=["A", "B", "C", "D", "E"])
# Create heatmap with annotations
sns.heatmap(data, annot=True)
plt.show()
Customizing Annotation Appearance
You can customize the annotation text size and formatting using annot_kws parameter ?
import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Create sample data
data = pd.DataFrame(np.random.randint(1, 100, (4, 4)),
columns=["Q1", "Q2", "Q3", "Q4"],
index=["Jan", "Feb", "Mar", "Apr"])
# Create heatmap with custom annotation styling
sns.heatmap(data,
annot=True,
annot_kws={"size": 10, "weight": "bold"},
fmt="d", # Integer formatting
cmap="Blues")
plt.title("Sales Data by Quarter")
plt.show()
Using Custom Annotation Values
You can also provide custom annotation values using a separate array ?
import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Create sample correlation data
data = pd.DataFrame([[1.0, 0.8, 0.6],
[0.8, 1.0, 0.7],
[0.6, 0.7, 1.0]],
columns=["X", "Y", "Z"],
index=["X", "Y", "Z"])
# Custom labels for annotations
labels = [["Perfect", "Strong", "Moderate"],
["Strong", "Perfect", "Strong"],
["Moderate", "Strong", "Perfect"]]
# Create heatmap with custom annotations
sns.heatmap(data,
annot=labels,
fmt="", # No formatting for strings
cmap="coolwarm",
annot_kws={"size": 9})
plt.title("Correlation Matrix with Labels")
plt.show()
Key Parameters
| Parameter | Description | Example |
|---|---|---|
annot |
Enable/disable annotations | annot=True |
annot_kws |
Customize annotation text | {"size": 10} |
fmt |
Number format string |
".2f" or "d"
|
Conclusion
Use annot=True to display cell values in Seaborn heatmaps. Customize appearance with annot_kws and use fmt to control number formatting for better readability.
Advertisements
