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")
018.08307.0130.0350412.070usachevrolet chevelle malibu
115.08350.0165.0369311.570usabuick skylark 320
218.08318.0150.0343611.070usaplymouth satellite
316.08304.0150.0343312.070usaamc rebel sst
417.08302.0140.0344910.570usaford 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)'seaborn-darkgrid')
    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.

Use Template