Menu

Tutorial9 min read

How to Create a Heatmap in Python: matplotlib, seaborn, and plotly

By Francesco VillasmuntaUpdated March 21, 2026
How to Create a Heatmap in Python: matplotlib, seaborn, and plotly

Heatmaps turn a matrix of numbers into a colour-coded grid, making it easy to spot patterns, outliers, and clusters that would be invisible in a table. They appear in gene expression studies, correlation analysis, confusion matrices, and any dataset where two categorical axes cross a continuous measurement.

Annotations

Set annot=True in seaborn to print values inside each cell — essential when the matrix is small enough to read.

Colourmap

Use coolwarm for diverging data (correlation, delta), and viridis or magma for sequential data.

Clustering

sns.clustermap reorders rows and columns by hierarchical clustering, revealing block structure automatically.

1. Basic heatmap with seaborn

sns.heatmap is the simplest starting point. Pass a 2-D array or DataFrame, set annot=True to show values, and choose a colourmap.

import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np

rng = np.random.default_rng(42)
data = rng.uniform(0, 1, (8, 8))

fig, ax = plt.subplots(figsize=(7, 6))
sns.heatmap(data, annot=True, fmt=".2f", cmap="viridis",
            linewidths=0.4, linecolor="black", ax=ax)
ax.set_title("Heatmap with Annotations")
plt.tight_layout()

2. Correlation matrix (masked upper triangle)

For correlation matrices, mask the redundant upper triangle with np.triu. Set vmin=-1, vmax=1 and use the coolwarm diverging palette so the neutral zero reads as white.

Try it

Try it now: create this heatmap from your data

Generate an annotated heatmap with a readable colormap and export-ready styling in one click.

Generate my heatmap

Newsletter

Get a weekly Python plotting tip

One concise tip each week for cleaner, faster scientific figures. Built for researchers who publish.

No spam. Unsubscribe anytime.
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

rng = np.random.default_rng(42)
df = pd.DataFrame(rng.standard_normal((100, 5)),
                  columns=["A", "B", "C", "D", "E"])
corr = df.corr()

mask = np.triu(np.ones_like(corr, dtype=bool))   # upper triangle mask

fig, ax = plt.subplots(figsize=(6, 5))
sns.heatmap(corr, mask=mask, annot=True, fmt=".2f",
            cmap="coolwarm", vmin=-1, vmax=1,
            square=True, linewidths=0.5, ax=ax)
ax.set_title("Correlation Matrix")
plt.tight_layout()

3. Clustered heatmap

sns.clustermap performs hierarchical clustering and reorders the rows and columns automatically. It creates its own figure, so do not pass ax manually.

import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np

rng = np.random.default_rng(42)
data = rng.uniform(0, 1, (12, 8))

# clustermap handles its own figure — do not use fig, ax
g = sns.clustermap(data, cmap="magma", figsize=(8, 7),
                   row_cluster=True, col_cluster=True,
                   linewidths=0.2)
g.ax_heatmap.set_title("Clustered Heatmap")
plt.tight_layout()

Colourmap reference

ColourmapBest for
viridisSequential data, perceptually uniform, colourblind-safe
magmaSequential data with dark background aesthetic
coolwarmDiverging data centred at zero (correlation, z-scores)
RdBu_rDiverging, publication-standard, colourblind-safe
YlOrRdSequential data where high values need emphasis

Common mistakes

  • Using rainbow colourmaps — jet and rainbow are not perceptually uniform and mislead readers. Use viridis or magma.
  • No colourbar — always include a colourbar with a label showing the variable name and units.
  • Annotating large matrices — annotation becomes unreadable above ~15×15 cells. Remove annot and rely on the colourbar instead.
  • Wrong vmin/vmax on diverging maps — set both symmetrically around zero so the neutral colour maps correctly.

Upload your matrix CSV and describe the heatmap you need — Plotivy generates the seaborn code with annotations, clustering, and the right colourmap.

Create your heatmap in Plotivy
Tags:#heatmap#seaborn#matplotlib#python#correlation

Related chart guides

Apply this tutorial directly in the chart gallery with ready-to-run prompts and examples.

Found this helpful? Share it with your network.

FV
Francesco Villasmunta

Experimental Physicist & Photonics Researcher

Hands-on experience in silicon photonics, semiconductor fabrication (DRIE/ICP-RIE), optical simulation, and data-driven analysis. Built Plotivy to help researchers focus on discoveries instead of data struggles.

More about the author

Visualize your own data

Apply the techniques from this article to your own datasets. Upload CSV, Excel, or paste data directly.

Start Analyzing - Free