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. Example: A daily sales and temperature record is kept by an ice cream store.
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))

🌐
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.
🌐
AskPython
askpython.com › python › examples › correlation-matrix-in-python
Correlation Matrix in Python - Practical Implementation - AskPython
September 18, 2020 - Further, we have used Seaborn Heatmaps to visualize the matrix. ... The variables ‘temp’ and ‘atemp’ are highly correlated with a correlation value of 0.99.
🌐
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})
🌐
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 ...
🌐
Real Python
realpython.com › numpy-scipy-pandas-correlation-python
NumPy, SciPy, and pandas: Correlation With Python – Real Python
March 18, 2026 - However, what you usually need are the lower left and upper right values of the correlation matrix. These values are equal and both represent the Pearson correlation coefficient for x and y. In this case, it’s approximately 0.76. This figure shows the data points and the correlation coefficients for the above example:
Find elsewhere
🌐
Statology
statology.org › home › how to create a correlation matrix in python
How to Create a Correlation Matrix in Python
December 22, 2021 - Step 3: Interpret the correlation matrix. The correlation coefficients along the diagonal of the table are all equal to 1 because each variable is perfectly correlated with itself. All of the other correlation coefficients indicate the correlation between different pairwise combinations of variables. For example:
🌐
Seaborn Line Plots
marsja.se › home › programming › python › create a correlation matrix in python with numpy and pandas
Create a Correlation Matrix in Python with NumPy and Pandas
August 22, 2023 - Now, we are in the final step to create the correlation table in Python with Pandas: ... Finally, if we want to use other methods (e.g., Spearman’s Rho) we’d just add the method='Spearman' argument to the corr method. See the image below. Here is a link to the example dataset. ... In this section, we are going to use NumPy and Pandas together with our correlation matrix (we have saved it as cormat: cormat = df.corr()).
🌐
datagy
datagy.io › home › python posts › calculate and plot a correlation matrix in python and pandas
Calculate and Plot a Correlation Matrix in Python and Pandas • datagy
April 18, 2023 - We can see that four of our columns were turned into column row pairs, denoting the relationship between two columns. For example, we can see that the coefficient of correlation between the body_mass_g and flipper_length_mm variables is 0.87.
🌐
Kaggle
kaggle.com › code › booleanwolf › correlation-matrix
Correlation Matrix
July 14, 2022 - Python · What is Correlation Matrix?Example of a Correlation MatrixInterpretationTemplate Code · This Notebook has been released under the Apache 2.0 open source license. Input1 file · arrow_right_alt · Output0 files · arrow_right_alt · Logs21.5 second run - successful ·
🌐
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 - The evident positive correlation of 0.888 between the two variables is strong, as it surpasses the 0.5 threshold and approaches 1.0. Pearson’s correlation coefficient can be used to evaluate the relationship between more than two variables.
🌐
GeeksforGeeks
geeksforgeeks.org › plotting-correlation-matrix-using-python
Plotting Correlation Matrix using Python - GeeksforGeeks
August 26, 2022 - It is very easy to understand the correlation using heatmaps it tells the correlation of one feature(variable) to every other feature(variable). In other words, A correlation matrix is a tabular data representing the ‘correlations’ between pairs of variables in a given data.
🌐
The Security Buddy
thesecuritybuddy.com › home › statistics for machine learning
How to calculate correlation matrix using Python? - The Security Buddy
February 9, 2023 - We can use the following Python code to calculate the correlation matrix between two random variables, X and Y, using the numpy Python module.
🌐
Towards Data Science
towardsdatascience.com › home › data science › demystifying the correlation matrix in data science
Demystifying the Correlation Matrix in Data Science | Towards Data Science
November 13, 2024 - In addition to the Pearson coefficient, other correlation coefficients can also be used, which are better suited to non-linear relationships, for example. In most cases, the results of the matrix are displayed using a heat map. Darker fields often indicate a higher correlation and lighter fields indicate a weaker correlation. In Python, the correlation matrix can be easily calculated from a DataFrame and visualized using seaborn.
🌐
Programiz
programiz.com › python-programming › pandas › correlation
Pandas Correlation (With Examples)
October 4, 2023 - Let's look at an example. import pandas as pd # create dataframe data = { "Temperature": [22, 25, 32, 28, 30], "Ice_Cream_Sales": [105, 120, 135, 130, 125] } df = pd.DataFrame(data) # calculate correlation matrix print(df.corr()) Output
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-create-a-correlation-matrix-using-pandas
How to Create a Correlation Matrix using Pandas? - GeeksforGeeks
May 27, 2025 - For example, given a time series [2, 3, 5, 7, 11], the autocorrelation at lag 1 can reveal how the series correlates with itself shifted by one time step. Let’s explore different metho ...
🌐
TutorialsPoint
tutorialspoint.com › how-to-create-a-correlation-matrix-using-pandas
How to Create a Correlation Matrix using Pandas?
April 20, 2023 - Pearson correlation (default): X Y Z X 1.000 0.100 -1.000 Y 0.100 1.000 -0.100 Z -1.000 -0.100 1.000 Spearman correlation: X Y Z X 1.000 0.100 -1.000 Y 0.100 1.000 -0.100 Z -1.000 -0.100 1.000 · The corr() method automatically handles only ...