[matplotlib] Use PatchCollection to draw a circled heat map


Draw a heatmap with circles

需要解决的问题:当数据维度较大时,热力图中显示数字会相当拥挤,最好能替换成相应的图形


As shown in the figure above, the data dimension is too high and the labeled heat map is very messy


1. Solutions

Use matplotlib.collections.PatchCollection to replace the text of the heatmap with graphics.

2. Code implementation

1. Import library

The code is as follows (example):

import pandas as pd
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.collections import PatchCollection

2. Draw a heat map with circles

The code is as follows (example):

# 导入数据
m=30
n=30
dat=-1+2*np.random.random((m, n))
whatever=pd.DataFrame(dat,columns=np.arange(m),index=np.arange(n))
ylabels = whatever.columns

# 数据处理
x, y = np.meshgrid(np.arange(m), np.arange(n-1,-1,-1))
s = np.array(whatever)
c = np.array(whatever)

fig, ax = plt.subplots(figsize=(13,13))

# 将标签改为圆圈
R = s/s.max()/2
circles = [plt.Circle((j,i), radius=r) for r, j, i in zip(R.flat, x.flat, y.flat)]
col = PatchCollection(circles, array=c.flatten(), cmap="RdBu")
ax.add_collection(col)

# 设置标签
ax.set(xticks=np.arange(m), yticks=np.arange(n-1,-1,-1),
       xticklabels=np.arange(m), yticklabels=ylabels)
ax.set_xticks(np.arange(m+1)-0.5, minor=True)
ax.set_yticks(np.arange(n+1)-0.5, minor=True)
ax.grid(which='minor',color='black',lw=1)

co=fig.colorbar(col)
co.ax.tick_params(axis='y', direction='out')

plt.show()

The output is shown in the figure belowinsert image description here

3. Limit the color bar range

You can see that the range of the color bar in the above picture is based on the actual data, not between [-1,1], which looks awkward

Just add the following line of code:

col.set_clim(-1,1) # 将颜色条范围设置为[-1,1]

The final result is shown in the figure below
insert image description here


Summarize

Through the PatchCollection function, not only can realize the heat map with circles, but also can customize various patterns, as shown in the figure below, if you are interested, you can explore by yourself.
insert image description here
The picture is from CHEN Y, WANG S, XIONG J, et al. Identifying facile material descriptors for Charpy impact toughness in low-alloy steel via machine learning [J]. J Mater Sci Technol , 2023, 132: 213-22.

Guess you like

Origin blog.csdn.net/KLZZ66/article/details/127751523