Hello! Welcome to the fourth lesson in our module on visualizing global movie data.
In the previous lesson, we learned how to create comparative bar charts. This was a great tool for a deep-dive comparison of movie preferences between a few selected countries. However, what if we want to see the big picture and compare the popularity of, say, the top 10 movies across 20 different countries all at once? A bar chart would become incredibly cluttered and difficult to read.
To solve this, we will now learn how to create a heatmap to compare movie popularity across multiple countries. Heatmaps are an excellent way to visualize matrix-like data, allowing you to spot patterns and trends across two dimensions simultaneously—in our case, countries and movies.
1. What is a Heatmap?
A heatmap is a graphical representation of data where the individual values contained in a matrix are represented as colors. It's like "painting by numbers" for data tables, making it much easier to spot high and low values, patterns, and outliers at a glance.
For our project, a heatmap will allow us to plot countries on one axis, movie titles on the other, and use color intensity to represent the viewing metric (e.g., popularity score or view count).
Seaborn Heatmap - How to Visualise Correlations and Data With Heatmaps in Python
To start, let's get a quick introduction to what heatmaps are and why they are useful. This video from Andy McDonald provides a concise explanation.
Please watch the first 45 seconds of the video. It clearly defines a heatmap and its purpose in understanding data trends and outliers.
This visualization technique is perfect for getting a bird's-eye view of how movie tastes vary across many different regions.

2. Preparing Your Data for a Heatmap
Just like with the grouped bar charts from our last lesson, the key to creating a heatmap is having your data in the correct "wide" or matrix-like format. The seaborn.heatmap() function we will be using expects its primary input to be a 2D array or a pandas DataFrame where:
- The DataFrame's index will form the y-axis (e.g., countries).
- The DataFrame's columns will form the x-axis (e.g., movie titles).
- The values within the DataFrame will be mapped to colors.
As you'll recall, the pivot_table() method in pandas is the perfect tool for this transformation. Given your consolidated dataset, you would first filter for the top N movies you want to compare, and then pivot the data.
Let's assume you have an aggregated DataFrame called movie_agg with columns country, movie_title, and popularity_score.
import pandas as pd
import numpy as np
# Sample aggregated data (long format)
data = {
'country': ['USA', 'USA', 'UK', 'UK', 'Canada', 'Canada', 'Germany', 'Germany'],
'movie_title': ['Home Alone', 'The Grinch', 'Love Actually', 'The Grinch', 'Home Alone', 'The Grinch', 'Drei Haselnüsse für Aschenbrödel', 'The Grinch'],
'popularity_score': [100, 85, 95, 88, 90, 92, 70, 75]
}
movie_agg = pd.DataFrame(data)
# Select a subset of movies and countries to make the heatmap readable
top_movies = ['Home Alone', 'The Grinch', 'Love Actually']
selected_countries = ['USA', 'UK', 'Canada', 'Germany']
subset_df = movie_agg[
movie_agg['movie_title'].isin(top_movies) &
movie_agg['country'].isin(selected_countries)
]
# Pivot the data to create a matrix: countries vs. movies
movie_matrix = subset_df.pivot_table(
index='country',
columns='movie_title',
values='popularity_score'
)
# Fill any missing values with 0, as this means the movie wasn't in the top list for that country
movie_matrix = movie_matrix.fillna(0)
print(movie_matrix)
Output:
movie_title Home Alone Love Actually The Grinch
country
Canada 90.0 0.0 92.0
Germany 0.0 0.0 75.0
UK 0.0 95.0 88.0
USA 100.0 0.0 85.0
This movie_matrix DataFrame is now perfectly structured to be visualized as a heatmap.
3. Creating and Customizing Heatmaps with Seaborn
We will use the Seaborn library, which is built on top of Matplotlib and provides a high-level interface for drawing attractive and informative statistical graphics. Its sns.heatmap() function is powerful and easy to use.
The Basic Heatmap
First, let's see how to create a simple heatmap from our pivoted data.
Seaborn heatmap | How to make a heatmap in Python Seaborn and adjust the heatmap style
This video from Kimberly Fessel demonstrates how to create a basic heatmap with Seaborn. The process is very straightforward once the data is in the right shape.
Watch from 00:51 to 03:42. Notice how she first prepares the data (using unstack, which is similar to pivot_table) and then passes the resulting DataFrame directly to sns.heatmap().
Applying this to our movie_matrix would look like this:
import seaborn as sns
import matplotlib.pyplot as plt
plt.figure(figsize=(10, 6)) # Adjust figure size for better readability
sns.heatmap(movie_matrix)
plt.title('Pre-Christmas Movie Popularity')
plt.show()
This simple command generates a complete heatmap. However, to make it more effective and visually appealing, we need to customize it.
Key Customizations
Let's explore the most important parameters for refining your heatmap. The Seaborn Heatmap using sns.heatmap() article is a great reference for the available parameters.
Seaborn Heatmap using sns.heatmap() | Python ...
This article from Indiana AI Production provides a detailed reference for all the parameters of the sns.heatmap() function. You don't need to memorize it, but it's good to know what's possible.
Briefly scan the syntax section to get an overview of the many parameters available in sns.heatmap(). We will focus on the most important ones next.
Now, let's dive into the most useful customizations.
Seaborn heatmap | How to make a heatmap in Python Seaborn and adjust the heatmap style
Kimberly Fessel's video provides excellent, clear explanations for the most common and impactful styling options. We'll watch it in segments.
Please watch the following segments: Choosing a Color Palette (5:15 - 7:44): This is crucial. Pay attention to the cmap argument and the difference between sequential and diverging palettes. For our movie scores, a sequential palette like 'viridis' or 'YlGnBu' is ideal. Adding Annotations (7:44 - 10:18): Learn how to display the actual data values on the heatmap using annot=True and how to format them with fmt. Final Styling (10:18 - 12:34): See how to add lines between cells with linewidths and linecolor to improve separation and clarity.
Let's apply these customizations to our movie example:
plt.figure(figsize=(10, 7))
sns.heatmap(
movie_matrix,
annot=True, # Show the data values in the cells
fmt=".0f", # Format annotations as integers
cmap='YlGnBu', # Use a color-blind friendly, sequential color map
linewidths=.5 # Add lines between cells
)
plt.title('Pre-Christmas Movie Popularity Comparison', fontsize=16)
plt.xlabel('Movie Title', fontsize=12)
plt.ylabel('Country', fontsize=12)
plt.xticks(rotation=45, ha='right') # Rotate x-axis labels for readability
plt.yticks(rotation=0)
plt.show()
This code produces a much more informative and polished visualization. You can immediately see which movies are popular where (e.g., Love Actually in the UK, Home Alone in the USA) and see the exact scores, all while getting a sense of the overall landscape from the colors.
Test your understanding!
You are given the following pivoted DataFrame named regional_favorites:
movie_title Elf Jingle All the Way Klaus
country
Australia 80 60 75
Brazil 40 55 85
Write a single call to sns.heatmap() that creates a heatmap of this data with the following specifications:
- The popularity scores should be displayed on the cells.
- The color map should be
'viridis'. - There should be a thin black line separating each cell.
Show answer
sns.heatmap(
regional_favorites,
annot=True,
cmap='viridis',
linewidths=0.5,
linecolor='black'
)
This call correctly uses annot=True to display the scores, sets the color map with cmap='viridis', and adds a 0.5-point wide black line between cells using linewidths and linecolor.
Conclusion
Today we've explored the heatmap, a powerful tool for visualizing relationships in matrix-like data. It overcomes the limitations of bar charts when you need to compare many items across many categories simultaneously.
Key Takeaways:
- Heatmaps use color to represent values in a 2D matrix, making them ideal for comparing movie popularity across many countries.
- Data preparation is key: You must use a method like
pivot_table()to transform your data into a "wide" format where the index represents one axis (countries) and columns represent the other (movies). - Seaborn's
sns.heatmap()function makes creating heatmaps simple. - Customization is crucial for clarity: Using parameters like
cmap,annot,fmt, andlinewidthstransforms a basic plot into an insightful and professional visualization.
In our next and final lesson, we will step back and look at all the visualizations we have created—the choropleth map, the bar charts, and our new heatmap. We will focus on how to synthesize the findings from these different views to identify cross-cultural trends and tell a compelling story about global pre-Christmas movie habits.