You can use pyplot.matshow() from matplotlib:

import matplotlib.pyplot as plt

plt.matshow(dataframe.corr())
plt.show()

Edit:

In the comments was a request for how to change the axis tick labels. Here's a deluxe version that is drawn on a bigger figure size, has axis labels to match the dataframe, and a colorbar legend to interpret the color scale.

I'm including how to adjust the size and rotation of the labels, and I'm using a figure ratio that makes the colorbar and the main figure come out the same height.


EDIT 2: As the df.corr() method ignores non-numerical columns, .select_dtypes(['number']) should be used when defining the x and y labels to avoid an unwanted shift of the labels (included in the code below).

f = plt.figure(figsize=(19, 15))
plt.matshow(df.corr(), fignum=f.number)
plt.xticks(range(df.select_dtypes(['number']).shape[1]), df.select_dtypes(['number']).columns, fontsize=14, rotation=45)
plt.yticks(range(df.select_dtypes(['number']).shape[1]), df.select_dtypes(['number']).columns, fontsize=14)
cb = plt.colorbar()
cb.ax.tick_params(labelsize=14)
plt.title('Correlation Matrix', fontsize=16);

Answer from jrjc on Stack Overflow
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ data science โ€บ create-a-correlation-matrix-using-python
Create a Correlation Matrix using Python - GeeksforGeeks
July 17, 2026 - NumPy provides a simple way to create a correlation matrix. We can use the np.corrcoef() function to find the correlation between two or more variables.
Top answer
1 of 16
477

You can use pyplot.matshow() from matplotlib:

import matplotlib.pyplot as plt

plt.matshow(dataframe.corr())
plt.show()

Edit:

In the comments was a request for how to change the axis tick labels. Here's a deluxe version that is drawn on a bigger figure size, has axis labels to match the dataframe, and a colorbar legend to interpret the color scale.

I'm including how to adjust the size and rotation of the labels, and I'm using a figure ratio that makes the colorbar and the main figure come out the same height.


EDIT 2: As the df.corr() method ignores non-numerical columns, .select_dtypes(['number']) should be used when defining the x and y labels to avoid an unwanted shift of the labels (included in the code below).

f = plt.figure(figsize=(19, 15))
plt.matshow(df.corr(), fignum=f.number)
plt.xticks(range(df.select_dtypes(['number']).shape[1]), df.select_dtypes(['number']).columns, fontsize=14, rotation=45)
plt.yticks(range(df.select_dtypes(['number']).shape[1]), df.select_dtypes(['number']).columns, fontsize=14)
cb = plt.colorbar()
cb.ax.tick_params(labelsize=14)
plt.title('Correlation Matrix', fontsize=16);

2 of 16
466

If your main goal is to visualize the correlation matrix, rather than creating a plot per se, the convenient pandas styling options is a viable built-in solution:

import pandas as pd
import numpy as np

rs = np.random.RandomState(0)
df = pd.DataFrame(rs.rand(10, 10))
corr = df.corr()
corr.style.background_gradient(cmap='coolwarm')
# 'RdBu_r', 'BrBG_r', & PuOr_r are other good diverging colormaps

Note that this needs to be in a backend that supports rendering HTML, such as the JupyterLab Notebook.


Styling

You can easily limit the digit precision (this is now .format(precision=2) in pandas 2.*):

corr.style.background_gradient(cmap='coolwarm').set_precision(2)

Or get rid of the digits altogether if you prefer the matrix without annotations:

corr.style.background_gradient(cmap='coolwarm').set_properties(**{'font-size': '0pt'})

The styling documentation also includes instructions of more advanced styles, such as how to change the display of the cell the mouse pointer is hovering over.


Time comparison

In my testing, style.background_gradient() was 4x faster than plt.matshow() and 120x faster than sns.heatmap() with a 10x10 matrix. Unfortunately it doesn't scale as well as plt.matshow(): the two take about the same time for a 100x100 matrix, and plt.matshow() is 10x faster for a 1000x1000 matrix.


Saving

There are a few possible ways to save the stylized dataframe:

  • Return the HTML by appending the render() method and then write the output to a file.
  • Save as an .xslx file with conditional formatting by appending the to_excel() method.
  • Combine with imgkit to save a bitmap
  • Take a screenshot (like I have done here).

Normalize colors across the entire matrix (pandas >= 0.24)

By setting axis=None, it is now possible to compute the colors based on the entire matrix rather than per column or per row:

corr.style.background_gradient(cmap='coolwarm', axis=None)


Single corner heatmap

Since many people are reading this answer I thought I would add a tip for how to only show one corner of the correlation matrix. I find this easier to read myself, since it removes the redundant information.

# Fill diagonal and upper half with NaNs
mask = np.zeros_like(corr, dtype=bool)
mask[np.triu_indices_from(mask)] = True
corr[mask] = np.nan
(corr
 .style
 .background_gradient(cmap='coolwarm', axis=None, vmin=-1, vmax=1)
 .highlight_null(color='#f1f1f1')  # Color NaNs grey
 .format(precision=2))

๐ŸŒ
Seaborn
seaborn.pydata.org โ€บ examples โ€บ many_pairwise_correlations.html
Plotting a diagonal correlation matrix โ€” seaborn 0.13.2 documentation
from string import ascii_letters import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt sns.set_theme(style="white") # Generate a large random dataset rs = np.random.RandomState(33) d = pd.DataFrame(data=rs.normal(size=(100, 26)), columns=list(ascii_letters[26:])) # Compute the correlation matrix corr = d.corr() # Generate a mask for the upper triangle mask = np.triu(np.ones_like(corr, dtype=bool)) # Set up the matplotlib figure f, ax = plt.subplots(figsize=(11, 9)) # Generate a custom diverging colormap cmap = sns.diverging_palette(230, 20, as_cmap=True) # Draw the heatmap with the mask and correct aspect ratio sns.heatmap(corr, mask=mask, cmap=cmap, vmax=.3, center=0, square=True, linewidths=.5, cbar_kws={"shrink": .5})
๐ŸŒ
The Great Speckled Bird
research.library.gsu.edu โ€บ python โ€บ correlation
Correlation - Python & Data Analysis - GSU Library Research Guides at Georgia State University
July 10, 2026 - One of the most effective ways to examine relationships across multiple variables is through a correlation matrix. A correlation matrix displays correlation values between all numerical variables in a dataset, making it easier to identify strong or weak relationships.
๐ŸŒ
YouTube
youtube.com โ€บ watch
How to make a correlation matrix in python - YouTube
import pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsimport numpy as npdata = pd.read_excel("C:/Users/Karina Adcock/Documents/data analysis...
Published: March 20, 2024
๐ŸŒ
Medium
tosinharold.medium.com โ€บ enhancing-correlation-matrix-heatmap-plots-with-p-values-in-python-41bac6a7fd77
Enhancing Correlation Matrix Heatmap Plots with P-values in Python | by Tosin Harold Akingbemisilu | Medium
July 10, 2025 - Enhancing Correlation Matrix Heatmap Plots with P-values in Python Correlation matrix plots are a valuable tool in data analysis, helping us visualize the relationships between variables in a โ€ฆ
Find elsewhere
๐ŸŒ
Simon Fraser University
sfu.ca โ€บ ~mjbrydon โ€บ tutorials โ€บ BAinPy โ€บ 08_correlation.html
7. Correlation and Scatterplots โ€” Basic Analytics in Python
Notice that every correlation matrix ... (or bottom, depending on your preferences) of every correlation matrix is redundant. The correlation between each variable and itself is 1.0, hence the diagonal. ... Python, and its libraries, make lots of things easy....
๐ŸŒ
Medium
medium.com โ€บ data-science โ€บ correlation-matrix-demystified-3ae3405c86c1
Correlation Matrix, Demystified. What is, how is it built and what is itโ€ฆ | by Giuseppe Mastrandrea | TDS Archive | Medium
July 7, 2022 - Now that we know how to build a correlation matrix and after the exploration of other forms of data visualization techniques in Python, we can ask ourselves what are the actual uses of this data structure.
๐ŸŒ
Towards AI
towardsai.com โ€บ home โ€บ publication โ€บ data analysis โ€บ building correlation matrix with p-values in python
Building Correlation Matrix With P-Values In Python | Towards AI
November 6, 2023 - Producing correlation output beyond the defaults in Python ยท If you're a fan of the correlation Matrix, like I am, this article is for you. This article is especially for folks who use Python to generate, display, and analyze correlation matrices.
๐ŸŒ
Built In
builtin.com โ€บ data-science โ€บ correlation-matrix
Introduction to the Correlation Matrix | Built In
We can easily implement a correlation matrix in Python because Python has a large library of support, and for statistical analysis, we can use Pandas and NumPy.
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ how-to-build-a-market-pulse-app-in-python-real-time-multi-asset
How to Build a Market Pulse App in Python: Real-Time & Multi-Asset
April 6, 2026 - In this tutorial, weโ€™ll build a minimal version of that in Python using Streamlit. The dashboard has three parts: a Pulse table that ranks the biggest movers across your watchlist ยท a Stress feed that emits event-style alerts instead of raw tick spam ยท a small Correlation card that updates based on the current volatility regime
๐ŸŒ
Data to Fish
datatofish.com โ€บ correlation-matrix-pandas
How to Create a Correlation Matrix using pandas
import pandas as pd import seaborn as sn import matplotlib.pyplot as plt data = {'A': [114, 93, 78, 84], 'B': [23, 19, 21, 18], 'C': [5, 8, 9, 11] } df = pd.DataFrame(data) corr_matrix = df.corr() sn.heatmap(corr_matrix, annot=True) plt.show() ... That's it! You just learned how to generate a correlations matrix using pandas.
๐ŸŒ
MachineLearningMastery
machinelearningmastery.com โ€บ home โ€บ blog โ€บ how to calculate correlation between variables in python
How to Calculate Correlation Between Variables in Python - MachineLearningMastery.com
November 17, 2023 - As with the Pearsonโ€™s correlation coefficient, the coefficient can be calculated pair-wise for each variable in a dataset to give a correlation matrix for review. For more help with non-parametric correlation methods in Python, see:
๐ŸŒ
Data to Viz
data-to-viz.com
From data to Viz | Find the graphic you need
See the dedicated page. Relationship between each pair of numeric variables ... A correlogram or correlation matrix allows to analyse the relationship between each pair of numeric variables of a matrix.
๐ŸŒ
Wikipedia
en.wikipedia.org โ€บ wiki โ€บ Correlation
Correlation - Wikipedia
2 weeks ago - The examples are sometimes said to demonstrate that the Pearson correlation assumes that the data follow a normal distribution, but this is only partially correct. The Pearson correlation can be accurately calculated for any distribution that has a finite covariance matrix, which includes most ...
๐ŸŒ
AlgorithmMinds
algorithmminds.com โ€บ home โ€บ how to create a correlation plot in python and r
How to Create Correlation Plot in Python and R
March 30, 2025 - Now, compute the correlation matrix using the cor() function. This matrix illustrates the correlation coefficients between pairs of variables, offering insights into their linear relationships.