Table of Contents
Adding a title to a Seaborn heatmap is a simple process. To do so, you must first create a figure object with Seaborn’s “heatmap” method and then use Matplotlib’s “set_title” method to add a title to the figure. An example of how to do this can be seen in the code below, where a figure object is created for a Seaborn heatmap and then the title “Heatmap Title” is added to the figure.
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')
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)
The following tutorials explain how to perform other common operations in seaborn: