Module 6 · Seaborn · Lesson 32 of 66
Matrix plots
Heat maps of correlations and pivot tables, and cluster maps that group similar rows.
In this lesson · about 12 minutes
- Turn a correlation table into a heat map
- Reshape data with pivot_table so it can be drawn as a matrix
- Use clustermap to group similar rows and columns
A heat map colors each cell of a table by its value. It needs data that's already shaped like a matrix, where the row labels and column labels both mean something. Two common ways to get there: a correlation table with df.corr(), or a pivot_table.
In pandas 2, corr() needs numeric_only=True when the table also has text columns.
Exercise
Correlation heat map
Draw a heat map of the correlations between the number columns of tips. Write each value in its cell with annot=True and use the 'coolwarm' color map.
Code that runs before yours
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset('tips')Pivot first, then draw
The flights data has one row per month: year, month, passengers. A pivot table turns it into months down the side, years across the top, and passengers in the cells.
Exercise
Passengers by month and year
Make the pivot table fp above (months as rows, years as columns, passengers as values), then draw it as a heat map with the 'magma' color map and white lines of width 1 between the cells.
Code that runs before yours
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset('tips')
flights = sns.load_dataset('flights')clustermap
sns.clustermap draws the same heat map but reorders rows and columns so similar ones sit together, with a tree on each side showing how they were grouped. Here the summer months end up next to each other. standard_scale=1 scales each column from 0 to 1 so the pattern within each year shows.
Exercises solved: 0 of 2
Noviq Academy's Data Science course is free and for learning. Python runs in your browser with Pyodide, which downloads about 20 MB the first time, plus a few more for scikit-learn. Your code and progress stay on this device. The salaries data is a sample of San Francisco's public pay records; the purchases, customers, housing, advertising and classified data are made up. The Titanic, tips, flights and iris data sets come from Seaborn's examples; the maps use public 2011 to 2014 US and world figures. The 911 data is a 20,000-call sample of Montgomery County, Pennsylvania's public 911 records; the movie ratings are the MovieLens 100K data from GroupLens Research; the reviews are a 3,000-review sample from the Yelp Dataset Challenge; the loans are public LendingClub data; the colleges are the College data from An Introduction to Statistical Learning; the bank notes, kyphosis and breast cancer data come from the UCI Machine Learning Repository. Spark and TensorFlow can't run in a browser, so those lessons use stand-ins that run here, and show the code for the real tools.