Heatmaps
DS 2023 | Communicating with Data

Overview¶
A heatmap displays a matrix of numbers as a grid of colored cells, where the color value in a cell is a function of the number value there.
Heatmaps show the relationship between two grouping variables and a measurement variable by using the visual channel of color to indicate intensity.
Use Cases¶
Visualizing wide-form data. Heatmaps can almost always be used to show the distribution of values in a wide table. As such, they are a good compliment to subplots generated from such tables.
Seeing structure in a large table at a glance. The advantage of a heatmap is that it shows two-dimensional patterns: blocks, stripes and criss-crosses, and gaps jump out that you would never notice scanning raw numbers.
Correlation and confusion matrices. A square matrix of relationships between variables (or predicted-vs-actual class counts) is often shown as a heatmap.
Contingency matrices. A heatmap can be used to show the pair-wise, co-ocurrence data. They are a good compliment to network diagrams of the same data.
Creating a heatmap from scratch¶
Let’s create a heatmap from scratch.
We’ll use a dataset of passenger counts on airline flights grouped by year and month.
This gives us a table of two grouping variables and a measurement one.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import seaborn as sns
flight_data_src = "https://virginia.box.com/shared/static/c8i3oyp8koeviixg2f9os7f0bgy869lf.csv"
flight = pd.read_csv(flight_data_src)
flight.info()
flight.head()<class 'pandas.DataFrame'>
RangeIndex: 144 entries, 0 to 143
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Years 144 non-null int64
1 Months 144 non-null str
2 Passengers 144 non-null int64
dtypes: int64(2), str(1)
memory usage: 4.4 KB
To ensure that the months display in the right order, we convert these into Categorical data type.
flight.Months.unique()<ArrowStringArray>
[ 'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December']
Length: 12, dtype: strflight['Months'] = pd.Categorical(flight['Months'], categories=flight.Months.unique(), ordered=True)First, we create a wide dataframe.
flight_wide = flight.pivot(columns='Years', index='Months', values='Passengers')
flight_wide.head()Then, we scale all the values to be in .
flight_wide_scaled = (flight_wide - flight_wide.min()) / (flight_wide.max() - flight_wide.min())
flight_wide_scaledNext, we map the scaled values to the corresponding value on a color scale.
Here we get a colormap object from Matplotlib called YlGnBu.
cmap = plt.colormaps["YlGnBu"]
cmapThe colormap as 256 color values, show above as a gradient.
cmap.N256We can take any number in and get the corresponding color code for it.
Here we see the results of converting .5, showing the result as an indexed series for demonstration purposes.
cmap_demo = pd.Series(cmap(.5), index=['r','g','b','a'])
cmap_demor 0.252687
g 0.711449
b 0.768381
a 1.000000
dtype: float64Often, we will convert these values to .
(cmap_demo * 255).astype(int)r 64
g 181
b 195
a 255
dtype: int64Or, we convert to hexadecimal, the format that color codes are often expressed.
(cmap_demo * 255).astype(int).map(hex)r 0x40
g 0xb5
b 0xc3
a 0xff
dtype: strNow, we convert the dataframe to RGBA values.
flight_wide_scaled_mapped = flight_wide_scaled.map(cmap)
flight_wide_scaled_mappedConvert the RGB tuples into HTML entities.
(
flight_wide_scaled_mapped
.unstack()
.apply(pd.Series)[[0,1,2]]
.multiply(255)
.astype(int)
.apply(lambda x: f"#{x[0]:02x}{x[1]:02x}{x[2]:02x}", axis=1)
.unstack()
.T
.style.map(lambda c: f'background-color: {c}')
)Using Matplotlib¶
Matplotlib’s plt.imshow() will take a 2D array and color each entry according to the specified colormap, defaulting to viridis.
plt.imshow(flight_wide)
plt.show()
plt.imshow(flight_wide)
plt.xticks(range(len(flight_wide.columns)), labels=flight_wide.columns, rotation=45, ha='right')
plt.yticks(range(len(flight_wide.index)), labels=flight_wide.index)
plt.xlabel('Month')
plt.ylabel('Year')
plt.show()
plt.imshow(flight_wide, cmap="viridis_r")
plt.xticks(range(len(flight_wide.columns)), labels=flight_wide.columns, rotation=45, ha='right')
plt.yticks(range(len(flight_wide.index)), labels=flight_wide.index)
plt.xlabel('Month')
plt.ylabel('Year')
plt.show()
plt.imshow(flight_wide, cmap="Blues")
plt.xticks(range(len(flight_wide.columns)), labels=flight_wide.columns, rotation=45, ha='right')
plt.yticks(range(len(flight_wide.index)), labels=flight_wide.index)
plt.xlabel('Month')
plt.ylabel('Year')
plt.show()
Using Seaborn¶
sns.heatmap(flight_wide, cmap='Reds')
plt.show()
sns.heatmap(flight_wide, cmap='viridis_r')
plt.show()
sns.heatmap(flight_wide.T, cmap='viridis_r')
plt.show()
plt.figure(figsize=(10,10))
sns.heatmap(flight_wide.T, annot=True, fmt='d', cmap='viridis_r')
plt.show()
Using Pandas¶
Because a heatmap is basically a colored-in wide-form table, Pandas let’s you style a dataframe as a heatmap with .style.background_gradient.
flight_wide.style.background_gradient() # The gradient goes along axis=0 by defaultflight_wide.style.background_gradient(axis=1)flight_wide.style.background_gradient(axis=None)flight_wide.style.background_gradient(axis=None, vmin=0, vmax=1000)flight_wide.style.background_gradient(axis=None, vmin=0, vmax=1000)flight_wide.style.background_gradient(axis=None, vmin=0, vmax=1000, cmap='YlGnBu')Using Plotly¶
import plotly.express as px
px.imshow(flight_wide, text_auto=True, height=1000, color_continuous_scale='viridis_r')