Python基于numpy绘制无seaborn/pandas依赖的行归一化线性百分比热力图
实现步骤和代码
我们只需要依赖numpy和matplotlib两个库即可完成需求,整体分为行占比计算、热力图绘制两个环节:
1. 核心逻辑说明
- 先对原始数组按行求和,将每个元素除以对应行的求和结果再乘以100,得到每个位置的行占比,保证每行总和为100%
- 直接使用matplotlib的
imshow方法绘制线性刻度热力图,无需引入seaborn、pandas库
2. 完整可运行代码
import numpy as np import matplotlib.pyplot as plt # 定义原始numpy数组 arr = np.array([ [0, 0, 0, 0, 0, 0, 2, 0, 2, 0, 0, 1, 26, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4], [21477, 61607, 21999, 17913, 22470, 32390, 11987, 41977, 81676, 20668, 17997, 15278, 46281, 19884], [5059, 13248, 5498, 3866, 2144, 6161, 2361, 8734, 16914, 3724, 4614, 3607, 11305, 2880], [282, 1580, 324, 595, 218, 525, 150, 942, 187, 232, 430, 343, 524, 189], [1317, 6416, 1559, 882, 599, 2520, 525, 2560, 19197, 729, 1391, 1727, 2044, 1198] ]) # 计算每行占比,保证每行总和为100% row_sums = arr.sum(axis=1, keepdims=True) row_ratio = arr / row_sums * 100 # 绘制热力图 plt.figure(figsize=(12, 6)) # 线性刻度渲染,cmap可根据需要调整为其他配色方案 im = plt.imshow(row_ratio, cmap='YlOrRd', aspect='auto', vmin=0, vmax=100) # 添加每个位置的占比文本标签 for i in range(row_ratio.shape[0]): for j in range(row_ratio.shape[1]): # 占比小于10%的用黑色文字,大于10%的用白色文字避免看不清 text_color = 'white' if row_ratio[i, j] > 10 else 'black' plt.text(j, i, f'{row_ratio[i, j]:.1f}%', ha='center', va='center', color=text_color, fontsize=8) # 配置图表样式 plt.colorbar(im, label='行占比(%)') plt.xlabel('列索引') plt.ylabel('行索引') plt.title('按行占比线性刻度热力图') plt.xticks(np.arange(row_ratio.shape[1])) plt.yticks(np.arange(row_ratio.shape[0])) plt.tight_layout() plt.show()
3. 效果说明
- 生成的热力图采用纯线性刻度,颜色深浅直接对应占比大小
- 每个单元格内标注了具体百分比数值,每行所有单元格百分比相加为100%
- 可通过调整
cmap参数修改配色,调整figsize参数修改画布大小,调整fontsize修改文字大小适配需求。
内容的提问来源于stack exchange,提问作者Makaveli_O
相关产品推荐
相关产品推荐

