How to draw a heatmap in Altair

Altair, a Python library, simplifies interactive visualization creation with a concise syntax. It seamlessly integrates with pandas, allowing for easy plotting from DataFrames. Its versatility spans various plot types and offers customization for publication-quality graphics. Altair is favored for exploratory data analysis and insightful visual storytelling in data science projects.

The heatmap in Altair

A heatmap in Altair is a graphical representation of data where values are encoded as colors in a two-dimensional grid. It visualizes the relationship between two variables by assigning colors to different combinations of values, allowing patterns and trends to be easily identified. Heatmaps are commonly used to represent matrices, correlation matrices, or any two-dimensional data where the intensity of a value is important.

To draw a heatmap in Altair, we can use the mark_rect() function. This function represents each data point as a rectangle with a color encoding corresponding to its value.

Code example

Here’s a basic example:

import altair as alt
import pandas as pd
import os
# Sample data
data = pd.DataFrame({
'x': ['A', 'B', 'C', 'D'] * 25,
'y': ['W', 'X', 'Y', 'Z'] * 25,
'value': [i+1 for i in range(100)]
})
# Create a heatmap
heatmap = alt.Chart(data).mark_rect().encode(
x='x:O',
y='y:O',
color='value:Q'
).properties(
width=300,
height=300
)
# Display the chart
heatmap.save('heatmap.html')
os.system('cat heatmap.html')

Explanation

  • Lines 1–3: We import Altair and other necessary libraries.

  • Lines 6–10: We create a pandas DataFrame named data with x, y, and value columns.

  • Lines 13–20: We initialize an Altair chart with data. We specify that it’s a heatmap (mark_rect). The mark_rect() function is used to represent each data point as a rectangle. The encode() function is used to map the 'x', 'y', and 'value' columns of the data to the x-axis, y-axis, and color respectively. The properties() sets the width and height of the plot.

  • Line 22: We save the chart using heatmap.save('heatmap.html'). It exports the chart to an HTML file named heatmap.html.

  • Line 23: We display the chart on the console.

We can customize the appearance of the heatmap further by adjusting color schemes, axis labels, titles, and other properties as needed.

Unlock your potential: Data visualization with the Altair series, all in one place!

To continue your exploration of data visualization using the Altair library, check out our series of Answers below:

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved