How to mask the upper triangle of a covariance matrix in sns.heatmap along with a covariance threshold?

Issue

To mask the covariances below a threshold I can use the following:

corr = df.corr(method = 'spearman')
sns.heatmap(corr, cmap = 'RdYlGn_r', mask = (corr <= T))

now how can I mask the upper triangle with the correlation threshold condition?

Solution

You can combine both masks using the logical or (|).

The example code below supposes you want to remove all correlations for which the absolute value is below some threshold:

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

df = pd.DataFrame(data=np.random.rand(7, 10), columns=[*'abcdefghij'])
corr = df.corr(method='spearman')
trimask = np.triu(np.ones_like(corr, dtype=bool))
sns.heatmap(corr, cmap='RdYlGn_r', mask=trimask | (np.abs(corr) <= 0.4), annot=True)

plt.tight_layout()
plt.show()

triangular heatmap with mask

Answered By – JohanC

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published