绘制带圆圈的热力图
需要解决的问题:当数据维度较大时,热力图中显示数字会相当拥挤,最好能替换成相应的图形
如上图所示,数据维度太高导致带标签的热力图很杂乱
一、解决方案
使用matplotlib.collections.PatchCollection来将热力图的文本替换成图形。
二、代码实现
1.引入库
代码如下(示例):
import pandas as pd
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.collections import PatchCollection
2.绘制带圆圈的热力图
代码如下(示例):
# 导入数据
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()
输出如下图所示
3.限制颜色条范围
可以看到上图颜色条范围以实际数据为准,不在[-1,1]之间,看起来很别扭
加入如下一行代码即可:
col.set_clim(-1,1) # 将颜色条范围设置为[-1,1]
最终结果如下图所示
总结
通过PatchCollection函数,不仅能够实现带圆圈的热力图,还可以自定义各种图案,如下图所示,有兴趣可以自己探索。
该图片来自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.