single
Visualizing Matrix Data
Swipe to show menu
A heatmap is a plot where data values are represented as colors in a matrix.
This is the standard way to visualize correlation matrices (how variables relate to each other) or time series grids (e.g., months vs. years).
Important: unlike scatterplot or barplot which take long lists of data, heatmap typically requires your data to be in a matrix (2D) format. This is often achieved using df.pivot_table() before plotting.
Key Parameters
annot=True: writes the data value in each cell;cmap: the color map (gradient) to use. Common choices:'viridis','coolwarm','magma';fmt: string formatting code to control how numbers look;'d': integers (no decimals);'.2f': floats with 2 decimal places;'g': general format (compact);linewidths/linecolor: adds distinct borders between cells.
Example
Here is a heatmap showing the correlation between numerical variables in the tips dataset.
12345678910111213141516171819import seaborn as sns import matplotlib.pyplot as plt # Load dataset df = sns.load_dataset('tips') # 1. Calculate Correlation Matrix (creates the grid) corr_matrix = df.corr(numeric_only=True) # 2. Plot Heatmap sns.heatmap( data=corr_matrix, annot=True, # Show numbers fmt='.2f', # 2 decimal places cmap='coolwarm',# Red-Blue gradient linewidths=1 # Separation lines ) plt.show()
Swipe to start coding
Visualize the number of passengers flying over the years. The data has already been reshaped into a matrix (upd_df) for you using pivot_table.
- Set the style to
'ticks'. Change the figure background color to'seagreen'('figure.facecolor'). - Create a heatmap:
- Pass
upd_dfas the data (this is the first argument, so you don't needdata=). - Use the
'viridis'color map (cmap). - Display the numbers in the cells (
annot=True). - Format the numbers using
'0.99g'(general format). - Set the color of the lines between cells to
'plum'(linecolor).
- Pass
- Display the plot.
Solution
Thanks for your feedback!
single
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat