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


Seaborn is a Python data visualization library based on Matplotlib. It provides a high-level interface for creating informative and attractive statistical graphics. Heatmaps are a popular visualization technique used to represent data in a 2D format. Seaborn provides a heatmap function that can be used to create heatmaps.

To add text in a heatmap cell annotations using seaborn in Python, we can use the annot parameter of the heatmap() function. The annot parameter is used to add annotations to the heatmap cells.

Here is an example code snippet that demonstrates how to add text in a heatmap cell annotations using seaborn in Python:

import seaborn as sns
import matplotlib.pyplot as plt

# Load the dataset
flights = sns.load_dataset("flights")

# Pivot the dataset to create a matrix
flights_matrix = flights.pivot("month", "year", "passengers")

# Create a heatmap with annotations
sns.heatmap(flights_matrix, annot=True, fmt="d")

# Show the plot
plt.show()

In the above code, we first load the flights dataset from seaborn. We then pivot the dataset to create a matrix using the pivot() function. We then create a heatmap using the heatmap() function and set the annot parameter to True to enable annotations. We also set the fmt parameter to "d" to format the annotations as integers. Finally, we show the plot using the show() function.

Another way to add text in a heatmap cell annotations using seaborn in Python is to use the heatmap() function with the annot_kws parameter. The annot_kws parameter is used to set the properties of the annotations such as the font size, font weight, and font color.

Here is an example code snippet that demonstrates how to add text in a heatmap cell annotations using seaborn in Python using the annot_kws parameter:

import seaborn as sns
import matplotlib.pyplot as plt

# Load the dataset
flights = sns.load_dataset("flights")

# Pivot the dataset to create a matrix
flights_matrix = flights.pivot("month", "year", "passengers")

# Create a heatmap with annotations
sns.heatmap(flights_matrix, annot=True, fmt="d", annot_kws={"fontsize":10, "fontweight":"bold", "color":"blue"})

# Show the plot
plt.show()

In the above code, we use the annot_kws parameter to set the font size to 10, font weight to bold, and font color to blue. This will make the annotations more visible and easier to read.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.