Back to Templates

Create a Heatmap
A heatmap is a useful visualization technique to show the magnitude of a phenomenon through varying color shade and intensity in two dimensions. The variation in color gives visual cues about how the phenomenon is clustered. Heatmaps can be used for webpage analysis to show where users have clicked or how far they have scrolled. Other examples include the display of eye-tracking test results or the representation of the number of foreclosures in the real estate market.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
%config InlineBackend.figure_format = 'retina'
# Upload your data as CSV and load as data frame
df = pd.read_csv("mpg.csv")
df.head()
mpg | cylinders | displacement | horsepower | weight | acceleration | model_year | origin | name | |
---|---|---|---|---|---|---|---|---|---|
0 | 18.0 | 8 | 307.0 | 130.0 | 3504 | 12.0 | 70 | usa | chevrolet chevelle malibu |
1 | 15.0 | 8 | 350.0 | 165.0 | 3693 | 11.5 | 70 | usa | buick skylark 320 |
2 | 18.0 | 8 | 318.0 | 150.0 | 3436 | 11.0 | 70 | usa | plymouth satellite |
3 | 16.0 | 8 | 304.0 | 150.0 | 3433 | 12.0 | 70 | usa | amc rebel sst |
4 | 17.0 | 8 | 302.0 | 140.0 | 3449 | 10.5 | 70 | usa | ford torino |
# Set your grouping variable and numeric variable
GROUP_VAR = 'origin'
NUM_VAR ='cylinders'
# Grouping by categorical variable 'origin', counting 'cylinders'
df_2 = df.groupby(GROUP_VAR)[NUM_VAR].value_counts()
df_2 = df_2.unstack().fillna(0)
plt.style.use('seaborn-darkgrid')
sns.heatmap(df_2,
cmap = 'RdBu', # set a colormap
center = 50, # set center of scale
vmin = 0, # set minimum value of scale
vmax = 100, # set maximum value of scale
annot = True, # enable annotations
fmt = ".0f", # number of decimal values of your annotations
linewidth = 1, # set widht of line between squares
linecolor = 'white', # set color of line between squares
# xticklabels = False, # show labels
# yticklabels = labels, # rename labels with list
square = True, # display perfect squares
annot_kws = {
'fontsize': 16, # define fontsize
'fontweight': 'normal', # set bold
'fontfamily': 'sans-serif' # monospace
}
)
# plt.xticks(rotation=45) # rotate labels of x axis
plt.yticks(rotation=45) # rotate labels of y axis
plt.title("Cylinder # by origin", # set a title
y = 1.05, # set position of title
size = 20); # set fontsize of title

Create a Heatmap
Show the magnitude of a phenomenon through varying color shade and intensity in two dimensions.