【matplotlib】使用PatchCollection绘制带圆圈的热力图


绘制带圆圈的热力图

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


如上图所示,数据维度太高导致带标签的热力图很杂乱


一、解决方案

使用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.

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值