Adjust the heat map of seaborn.
Specifically, it rotates and masks the heatmap.
I'm using Python 3.7.1. The usage environment is Jupyter notebook.
import numpy as np
import seaborn as sns
Make the heat map go round and round.
heat = np.array([[0,1],[2,3]])
#input
print(
np.rot90(heat, k=0),
np.rot90(heat, k=1),
np.rot90(heat, k=2),
np.rot90(heat, k=3),
sep='\n\n')
#output
[[0 1]
[2 3]]
[[1 3]
[0 2]]
[[3 2]
[1 0]]
[[2 0]
[3 1]]
You can see that it is rotating by 90 °.
#Rewrite DATA as the matrix you want to visualize
sns.heatmap(DATA, cmap='Blues',
square=True, cbar_kws={"shrink": .5},
xticklabels=0, yticklabels=0)
Visualizing the four results of "3.1. Rotate the matrix first" You can get the result of rotation by turning around as shown in the figure below.
heat = np.array([[0,1],[2,3]])
#input
print(
np.rot90(heat, k=1).T, # == np.rot90(heat, k=2)[::-1],
np.rot90(heat, k=2).T, # == np.rot90(heat, k=3)[::-1],
np.rot90(heat, k=3).T, # == np.rot90(heat, k=4)[::-1],
np.rot90(heat, k=4).T, # == np.rot90(heat, k=5)[::-1],
sep='\n\n')
#output
[[1 0]
[3 2]]
[[3 1]
[2 0]]
[[2 3]
[0 1]]
[[0 2]
[1 3]]
You can see that the * heat * inverted matrix is rotated by 90 °.
When visualized, it will look like the figure below.
Mask where you don't need a heatmap.
Please change it according to your purpose.
heat = np.ones((3,3))
# 1.Mask the upper triangular matrix
mask = np.zeros((len(heat),len(heat)))
mask[np.triu_indices_from(mask, k=0)] = True # k=Include diagonal component at 1
# 2.Mask the lower triangular matrix
mask = np.zeros((len(heat),len(heat)))
mask[np.tril_indices_from(mask, k=0)] = True # k=Include diagonal component at 1
# 3.Mask the diagonal matrix
mask = np.eye(len(heat))
# 4.Mask a specific value
mask = np.zeros((len(heat),len(heat)))
mask[np.where(heat==1)] = True # np.where()Put the condition in
#Rewrite DATA as the matrix you want to visualize
sns.heatmap(DATA, cmap='Blues',
square=True, cbar_kws={"shrink": .5},
xticklabels=0, yticklabels=0, mask=mask)
Let's start with the one without the mask.
No mask
Mask the upper triangular matrix
Mask the lower triangular matrix
Mask the diagonal matrix
Mask specific values
Suppose you want to convert that component to "0" instead of masking it. Specifically, get the matrix when mask is 1, and rewrite the corresponding part to 0.
for i in range(len(np.where(mask[:]==1)[0])):
heat[np.vstack(np.where(mask[:]==1)).T[i][0], np.vstack(np.where(mask[:]==1)).T[i][1]]=0
I wrote a lot about adjusting the heat map of seaborn, but how was it? I would appreciate it if you could point out any points that are difficult to understand or incorrect.
· Np.rot90 to rotate the NumPy array ndarray https://note.nkmk.me/python-numpy-rot90/
・ Numpy.triu_indices https://docs.scipy.org/doc/numpy/reference/generated/numpy.triu_indices.html
Recommended Posts