0

I have computed a covariance of 26 inputs from another software. I have an existing table of the results. See image below: enter image description here

What I want to do is enter the table as a pandas dataframe and plot the matrix. I have seen the thread here: Plot correlation matrix using pandas. However, the aforementioned example, computed the covariance first and plotted the 'covariance' object. In my case, I want to plot the dataframe object to look like the covariance matrix in the example.

Link to data: HERE.

Nikko
  • 1,410
  • 1
  • 22
  • 49
  • 1
    You can use seaborn.heatmap(name_of_your_dataframe) to do it. This feature of the seaborn library is often used to graphically display a correlation matrix. – stukituk Jan 15 '23 at 13:31
  • And of course you can change the colors with the 'cmap' parameter. One of my favorites for covariance matrix: 'coolwarm'. Here - https://www.kaggle.com/code/asimislam/python-colors-color-cmap-palette you can find another pallets – stukituk Jan 15 '23 at 13:42

2 Answers2

2

a clean option, in my opinion, from this other answer: How to plot only the lower triangle of a seaborn heatmap?

import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline

df = pd.read_excel('Covariance Matrix.xlsx', header=None)

# Getting the Upper Triangle of the co-relation matrix
matrix = np.triu(df)

# using the upper triangle matrix as mask 
fig, ax = plt.subplots(figsize=(12,8))
sns.heatmap(df, ax=ax, fmt='.1g', annot=True, mask=matrix)
plt.show()

triangular heatmap

hope this helps

el_Rinaldo
  • 970
  • 9
  • 26
1

IIUC, you can use seaborn.heatmap with annot=True :

plt.figure(figsize=(6, 4))

(
    pd.read_excel("/tmp/Covariance Matrix.xlsx", header=None)
        .pipe(lambda df: sns.heatmap(df.sample(10).sample(10, axis=1), annot=True, fmt=".1f"))
);

# for a sample of 10 rows / 10 columns

Output :

enter image description here

And, as suggested by stukituk in the comments, you can add cmap="coolwarm" for colors :

enter image description here

Timeless
  • 22,580
  • 4
  • 12
  • 30