How to create a heatmap with an arbitrary domain in Python

image.png

Heatmap is a powerful way to illustrate $ f = (x, y) $ data.

Seaborn is famous in Python, but the domain of x and y is limited to1,2, ...respectively. Anyway, you want to do it in any domain. I will explain how to do it with reference to scikit-learn sample code.

Awkward but capable of handling any function

import numpy as np
import matplotlib.pyplot as plt
x = np.arange(-2,2,0.1)
y = np.arange(-2,2,0.1)
xx,yy = np.meshgrid(x,y)
z = np.zeros((len(x),len(y)))
for i in range(len(x)):
    for j in range(len(y)):
        v = np.array([xx[i][j],yy[i][j]])
        r = np.linalg.norm(v)
        z[i][j] = np.exp(-r)
plt.figure(figsize=(5,5))
plt.contourf(x,y,z,cmap='coolwarm')
plt.show()

The content of the for statement is actually $ f (x, y) $, and in the sample code above, as an example,

f(x,y) = e^{\frac{-1}{\sqrt{x^2+y^2}}}

Is implemented. It's complicated, so I've divided it into three lines, but what I'm doing is the same.

This works for all functions, but using the for statement is awkward. Above all, it is inconvenient because it does not correspond to the pattern that it is okay to run the matrix once and the shape of various machine learning prediction models (generally the number of data x input vector).

Number of data x input vector

import numpy as np
import matplotlib.pyplot as plt

def model(xy):
    ar = np.array([-2,1])
    return np.matmul(xy,ar)

x = np.arange(-2,2,0.1)
y = np.arange(-2,2,0.1)
xx,yy = np.meshgrid(x,y)
xx = xx.reshape(-1,1)
yy = yy.reshape(-1,1)
xy = np.concatenate([xx,yy],1)
z = model(xy)
z = z.reshape(-1,len(x))
plt.figure(figsize=(5,5))
plt.contourf(x,y,z,cmap='coolwarm')
plt.show()

The shape of x and y is shaped. It looks like the figure below.

image.png

This format can accommodate functions such as lda.precdict () and model () (PyTorch, etc.).

bonus

If you use pcolormedh instead of contourf, the grid will be displayed. It looks pretty, but I personally prefer contourf because it makes the data trends more difficult to understand.

image.png

import numpy as np
import matplotlib.pyplot as plt
x = np.arange(-2,2,0.01) #Resolution 0.To 01
y = np.arange(-2,2,0.01) #Resolution 0.To 01
xx,yy = np.meshgrid(x,y)
z = np.zeros((len(x),len(y)))
for i in range(len(x)):
    for j in range(len(y)):
        v = np.array([xx[i][j],yy[i][j]])
        r = np.linalg.norm(v)
        z[i][j] = np.exp(-r)
plt.figure(figsize=(5,5))
plt.pcolormesh(x,y,z,cmap='coolwarm') #Change here
plt.show()

Recommended Posts

How to create a heatmap with an arbitrary domain in Python
How to create a JSON file in Python
How to convert / restore a string with [] in python
How to create an image uploader in Bottle (Python)
[Python] How to create a 2D histogram with Matplotlib
How to convert an array to a dictionary with Python [Application]
[Python Kivy] How to create an exe file with pyinstaller
How to get a stacktrace in python
How to make a string into an array or an array into a string in Python
How to create an instance of a particular class from dict using __new__ () in python
How to read a CSV file with Python 2/3
How to create a Python virtual environment (venv)
[REAPER] How to play with Reascript in Python
How to clear tuples in a list (Python)
How to embed a variable in a python string
I want to create a window in Python
How to crop an image with Python + OpenCV
Create a virtual environment with conda in Python
Create an image with characters in python (Japanese)
Steps to create a Twitter bot with python
How to notify a Discord channel in Python
How to use tkinter with python in pyenv
Create a new page in confluence with Python
How to create a multi-platform app with kivy
[Python] How to draw a histogram in Matplotlib
How to create a Rest Api in Django
How to draw a vertical line on a heatmap drawn with Python seaborn
3. Natural language processing with Python 1-2. How to create a corpus: Aozora Bunko
Create a function in Python
Create a dictionary in Python
[Python] How to draw a line graph with Matplotlib
How to do hash calculation with salt in Python
Explain in detail how to make sounds with python
[Blender x Python] How to create an original object
How to create a submenu with the [Blender] plugin
[Python] How to expand variables in a character string
How to drop Google Docs in one folder in a .txt file with python
Create a plugin to run Python Doctest in Vim (2)
Create a plugin to run Python Doctest in Vim (1)
I want to work with a robot in python.
Create a random number with an arbitrary probability density
Create a heatmap with pyqtgraph
[python] Create a date array with arbitrary increments with np.arange
Searching for an efficient way to write a Dockerfile in Python with poetry
How to develop in Python
How to execute a command using subprocess in Python
Create a directory with python
Create a fake Minecraft server in Python with Quarry
How to create a kubernetes pod from python code
[Python] How to draw a scatter plot with Matplotlib
How to get a list of files in the same directory with python
[Python] How to create a local web server environment with SimpleHTTPServer and CGIHTTPServer
How to identify the element with the smallest number of characters in a Python list?
Create an exe file that works in a Windows environment without Python with PyInstaller
[GCF + Python] How to upload Excel to GCS and create a new table in BigQuery
A story about how Windows 10 users created an environment to use OpenCV3 with Python 3.5
How to use NUITKA-Utilities hinted-compilation to easily create an executable file from a Python script
How to use python multiprocessing (continued 3) apply_async in class with Pool as a member
How to slice a block multiple array from a multiple array in Python
Create a list in Python with all followers on twitter
How to output a document in pdf format with Sphinx