6

I have this code from seaborn documentation to generate a mask for the upper triangle of a given correlation matrix

# Compute the correlation matrix
corr = d.corr()

# Generate a mask for the upper triangle

mask = np.zeros_like(corr, dtype=np.bool)
mask[np.triu_indices_from(mask)] = True

how would one achieve the invert, a mask for the lower triangle?

3 Answers3

11

Simply replace triu_indices_from with tril_indices_from:

mask = np.zeros_like(corr, dtype=np.bool)
mask[np.tril_indices_from(mask)] = True
MEE
  • 2,114
  • 17
  • 21
1

Take the transpose of your matrix:

mask = mask.T

mask
array([[ True, False, False, False, False],
       [ True,  True, False, False, False],
       [ True,  True,  True, False, False],
       [ True,  True,  True,  True, False],
       [ True,  True,  True,  True,  True]])

mask.T
array([[ True, False, False, False, False],
       [ True,  True, False, False, False],
       [ True,  True,  True, False, False],
       [ True,  True,  True,  True, False],
       [ True,  True,  True,  True,  True]])

However this is more of a workaround, the correct solution is @john 's

yatu
  • 86,083
  • 12
  • 84
  • 139
1

You can simply transpose the mask that you have:

mask = np.zeros_like(corr, dtype=np.bool).T
mask[np.triu_indices_from(mask)] = True
Tim
  • 2,756
  • 1
  • 15
  • 31