Add diagonal lines (hatch) to heatmap (python, matplotlib)

Introduction

I wanted to draw a diagonal line ('/') on the part showing a specific value on the heat map, so make a note.

Thing you want to do

In the following heat map, I want to make the part of a specific value look good with diagonal lines.

%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np

np.random.seed(0)
Z =np.random.rand(10, 10)
Zm = Z * 0
Z[3:5, 5:8] = 1
fig, ax = plt.subplots(figsize=(9, 7))
ax1 = ax.pcolormesh(Z)
fig.colorbar(ax1)

image.png

In the figure above, some values in the figure are set to 1 with Z [3: 5, 5: 8] = 1. Draw a diagonal line in this Z [3: 5, 5: 8] part.

Solution

The final code is below.

np.random.seed(0)
Z =np.random.rand(10, 10)
Zm = Z * 0
Z[3:5, 5:8] = 1
fig, ax = plt.subplots(figsize=(9, 7))
ax1 = ax.pcolormesh(Z)

Zm = np.ma.masked_where(Z!=1, Z)
ax2 = ax.pcolor(Zm, hatch='/', edgecolor='grey',facecolor='none', linewidth=0.0)

fig.colorbar(ax1)
```
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/167418/2a7abe1d-cb07-25f7-81e1-5ddc58bb75e1.png)

#what are you doing
In the above code, the following two lines are different from the first.

``````python
Zm = np.ma.masked_where(Z!=1, Z)
ax2 = ax.pcolor(Zm, hatch='/', edgecolor='grey',facecolor='none', linewidth=0.0)
```

## Line 1: Matrix mask
 In order to show only a part with diagonal lines, the matrix (`Zm`) representing that part is created in the first line of the code.

 By using `numpy.ma.masked_where`, you can create a matrix in which the part corresponding to the condition is invalidated (masked).
 Reference: [numpy.ma.masked_where official documentation](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ma.masked_where.html)

 The original matrix (`Z`) and the masked matrix (`Zm`) are as follows.
 <img width="616" alt="スクリーンショット 2019-12-03 13.53.23.png " src="https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/167418/d964c787-cd0a-37c3-bbd3-bfeeb49b3b73.png ">


 <img width="616" alt="スクリーンショット 2019-12-03 13.53.33.png " src="https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/167418/67c775c9-f2fa-a1b2-c7fa-39baad0c821c.png ">

 Looking at the contents of the matrix, in `Zm`, except for the elements corresponding to the conditional expression (`Z! = 1`), they are represented by `--`.
 By using this matrix `Zm` when plotting, you can plot by ignoring the part corresponding to the conditional expression.

## 2nd line: Draw diagonal lines with hatch
 Reference: [python – How can I fill the area with only hatch (no background color) in matplotlib 2.0? ](Https://codeday.me/jp/qa/20190618/1041536.html)

 In the second line of code, the matrix `Zm` is used to draw the diagonal lines.
 In `matplotlib.pyplot.pcolor`, the following pattern of hatch can be used.
> /   - diagonal hatching
\   - back diagonal
|   - vertical
-   - horizontal
+   - crossed
x   - crossed diagonal
o   - small circle
O   - large circle
.   - dots
*   - stars

 Reference: [matplotlib.collections.Collection.set_hatch](https://matplotlib.org/3.1.1/api/collections_api.html#matplotlib.collections.Collection.set_hatch)

 The options used here are as follows.

 --ʻEdgecolor`: hatch color
 --`facecolor`: The background color of hatch. By setting it to'none', only hatch can be displayed while leaving the color of the heat map.
 --`linewidth`: Grid thickness. If you specify a value greater than 0, the grid will be displayed.

 The appearance of the figure when the options are changed is as follows.
 (Same as the final code except for the line ʻax.pcolor`)

``````python
ax2 = ax.pcolor(Zm, hatch='/', edgecolor='grey',facecolor='none', linewidth=1.0)
```

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/167418/aa00bcaf-26c2-822a-9aba-c1bb5a55624c.png)


``````python
ax2 = ax.pcolor(Zm, hatch='/', edgecolor='grey',linewidth=0.0)
```
 ![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/167418/13cdac85-38eb-4d3c-1225-fce630d3095e.png)

``````python
ax2 = ax.pcolor(Zm, hatch='/', edgecolor='red',facecolor='none', linewidth=0.0)
```
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/167418/65ae65d2-8ae4-5c0c-8490-4c04dcd4a237.png)


###List of reference sites
[numpy.ma.masked_where official documentation](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ma.masked_where.html)
[python – matplotlib 2.How can I fill the area with 0 with only the hatch (no background color)?](https://codeday.me/jp/qa/20190618/1041536.html)
[matplotlib.collections.Collection.set_hatch](https://matplotlib.org/3.1.1/api/collections_api.html#matplotlib.collections.Collection.set_hatch)



Recommended Posts

Add diagonal lines (hatch) to heatmap (python, matplotlib)
Heatmap with Python + matplotlib
How to add new data (lines and plots) using matplotlib
Add cumulative ratio to matplotlib histogram
Add Python 2.7 Japanese documentation to Dash.app
Heatmap with Dendrogram in Python + matplotlib
Add TRACE log level to Python ...?
Add 95% confidence intervals on both sides to the diagram with Python / Matplotlib
Add cumulative ratio to matplotlib bar chart
[Python] Add total rows to Pandas DataFrame
Add Gaussian noise to images with python2.7
How to add python module to anaconda environment
Add a Python virtual environment to VSCode
[Python] Add comments to standard input files
Want to add type hints to your Python decorator?
Just add the python array to the json data
[Python] How to draw multiple graphs with Matplotlib
[Python] Memo to translate Matplotlib into Japanese [Windows]
How to add a Python module search path
To add a module to python put in Julialang
Speed: Add element to end of Python array
[Python] How to draw a histogram in Matplotlib
Updated to Python 2.7.9
#Python basics (#matplotlib)
My matplotlib (python)
"Backport" to python 2
[Python] [Django] How to use ChoiceField and how to add options
How to add help to HDA (with Python script bonus)
I tried to summarize how to use matplotlib of python
[Python] How to draw a line graph with Matplotlib
How to write string concatenation in multiple lines in Python
Add information to the bottom of the figure with Matplotlib
How to add page numbers to PDF files (in Python)
PyInstaller memorandum Convert Python [.py] to [.exe] with 2 lines
How to add color bars in matplotlib bar plot
[Python] How to create a 2D histogram with Matplotlib
[Introduction to Python] Basic usage of the library matplotlib
Introduction to Python numpy pandas matplotlib (~ towards B3 ~ part2)
[Python] How to draw a scatter plot with Matplotlib
[Python] Road to a snake charmer (5) Play with Matplotlib