How to Add Title to Seaborn Heatmap (With Example)


You can use the following basic syntax to add a title to a heatmap in seaborn:

import matplotlib.pyplot as plt
import seaborn as sns

#create heatmap
sns.heatmap(df)

#add title
plt.title('This is my title')

The following example shows how to use this syntax in practice.

Example: Add Title to Heatmap in Seaborn

Suppose we have the following pandas DataFrame that contains information about points scored by various basketball players during five consecutive years:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'year': [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5],
                   'player': ['A', 'A', 'A', 'A', 'A', 'B', 'B',
                              'B', 'B', 'B', 'C', 'C', 'C', 'C', 'C'],
                   'points': [8, 12, 14, 14, 15, 10, 15, 19, 29, 13,
                              10, 14, 22, 24, 25]})

#pivot DataFrame
df = df.pivot('player', 'year', 'points')

#view DataFrame
print(df)

year     1   2   3   4   5
player                    
A        8  12  14  14  15
B       10  15  19  29  13
C       10  14  22  24  25

If we use the heatmap() function to create a heatmap in seaborn, no title will be added to the heatmap by default:

import seaborn as sns

#create heatmap
sns.heatmap(df, linewidth=.3)

However, we can use the title() function from matplotlib to quickly add a title to the heatmap:

import matplotlib.pyplot as plt
import seaborn as sns

#create heatmap
sns.heatmap(df, linewidth=.3)

#add title to heatmap
plt.title('Points Scored by Players Each Year')

seaborn heatmap with title

Also note that we can use the following arguments within the title() function to modify the appearance of the title:

  • loc: Location of the title text
  • color: Color of the title text
  • size: Font size of the title text

The following code shows how to add a title that is left-aligned, has a red font color, and a font size of 14:

import matplotlib.pyplot as plt
import seaborn as sns

#create heatmap
sns.heatmap(df, linewidth=.3)

#add customized title to heatmap
plt.title('Points Scored by Players Each Year', loc='left', color='red', size=14)

seaborn heatmap with customized title

Feel free to modify the arguments in the title() function to create the exact title you’d like.

Additional Resources

The following tutorials explain how to perform other common operations in seaborn:

How to Adjust the Size of Heatmaps in Seaborn
How to Add a Title to Seaborn Plots
How to Create Subplots in Seaborn

One Reply to “How to Add Title to Seaborn Heatmap (With Example)”

Leave a Reply

Your email address will not be published. Required fields are marked *