Python: Rotate and mask seaborn heatmaps

1.First of all

Adjust the heat map of seaborn.

Specifically, it rotates and masks the heatmap.

2. Preparation

2.1. Environment

I'm using Python 3.7.1. The usage environment is Jupyter notebook.

2.2. Required libraries

import numpy as np
import seaborn as sns

3. Rotation of heat map

Make the heat map go round and round.

3.1. First, rotate the matrix

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 °.

3.2. Visualization with heat map

#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.

1.png

3.2. Invert the matrix left and right

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.

2.png

4. Heatmap mask

Mask where you don't need a heatmap.

4.1. Mask pretreatment

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

4.2. Visualization with heat map

#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.

  1. No mask 0.png

  2. Mask the upper triangular matrix a.png

  3. Mask the lower triangular matrix c.png

  4. Mask the diagonal matrix k.png

  5. Mask specific values f.png

4.3. Convert to 0 instead of mask

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

5. Finally

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.

Reference URL

· 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

Python: Rotate and mask seaborn heatmaps
[python] Compress and decompress
Python and numpy tips
[Python] pip and wheel
Batch design and python
Python iterators and generators
Python packages and modules
Vue-Cli and Python integration
Ruby, Python and map
python input and output
Python and Ruby split
Rotate and scale the image before cropping [python] [OpenCV]
Python3, venv and Ansible
Python asyncio and ContextVar
Programming with Python and Tkinter
Encryption and decryption with Python
Python: Class and instance variables
3-3, Python strings and character codes
Python 2 series and 3 series (Anaconda edition)
Python and hardware-Using RS232C with Python-
Python on Ruby and angry Ruby on Python
Python indentation and string format
Python real division (/) and integer division (//)
Install Python and Flask (Windows 10)
About python objects and classes
About Python variables and objects
Apache mod_auth_tkt and Python AuthTkt
Å (Ongustromu) and NFC @ Python
Understand Python packages and modules
# 2 [python3] Separation and comment out
Python shallow copy and deep copy
Python and ruby slice memo
Python installation and basic grammar
I compared Java and Python!
Python shallow and deep copy
About Python, len () and randint ()
About Python datetime and timezone
Install Python 3.7 and Django 3.0 (CentOS)
Python environment construction and TensorFlow
Python class variables and instance variables
Ruby and Python syntax ~ branch ~
[Python] Python and security-① What is Python?
Stack and Queue in Python
python metaclass and sqlalchemy declareative
Fibonacci and prime implementations (python)
Python basics: conditions and iterations
Python bitwise operator and OR
Python debug and test module
Python list and tuples and commas
Python variables and object IDs
Python list comprehensions and generators
About Python and regular expressions
python with pyenv and venv
Unittest and CI in Python
Maxout description and implementation (Python)
[python] Get quotient and remainder
Python 3 sorted and comparison functions
[Python] Depth-first search and breadth-first search
Identity and equivalence Python is and ==
Source installation and installation of Python
Python or and and operator trap